Compare commits

..
252 changed files with 2238 additions and 12830 deletions
+5 -5
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": 429719786,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
+7 -10
View File
@@ -1,8 +1,7 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
@@ -23,23 +22,21 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: cadcraft
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
# callee job may bind the existing release environment and export keys in its signing step.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
-20
View File
@@ -1,20 +0,0 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1 -1
View File
@@ -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 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/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/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
+84 -1270
View File
File diff suppressed because it is too large Load Diff
+32 -36
View File
@@ -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 = "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" }
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" }
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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -74,12 +74,8 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
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"] }
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"] }
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 }
@@ -89,7 +85,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 = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
@@ -121,23 +117,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 = "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" }
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" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
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" }
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" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+4 -10
View File
@@ -89,15 +89,9 @@
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 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.
- **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.
- **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
@@ -120,7 +114,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, 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 |
| 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) |
| 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 |
-1
View File
@@ -60,7 +60,6 @@ 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.
-3
View File
@@ -154,9 +154,6 @@ 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(())
}
@@ -1,41 +0,0 @@
//! `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);
}
-3
View File
@@ -1,9 +1,6 @@
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;
+2 -2
View File
@@ -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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
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" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+2 -5
View File
@@ -54,12 +54,11 @@ 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 hand the frame's root values to the UI runtime.
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.0.before_input(ctx);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
/// Preferences and validated panel placement survive reloads; egui memory is not kept.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
@@ -135,7 +134,6 @@ 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;
@@ -168,7 +166,6 @@ 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());
+1 -1
View File
@@ -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 = cadcraft_ui_egui::docking::Workspace::default();
invalid.docking.layout.root = None;
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();
+7 -3
View File
@@ -41,18 +41,22 @@ 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).
# 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.
# `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
+40 -52
View File
@@ -61,6 +61,9 @@ 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,
@@ -138,18 +141,17 @@ 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 hand the frame's root values to the UI
/// runtime.
/// Apply the desktop-theme fallback, forward raw input to `CadApp`, and capture Tab at the command line.
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);
self.cad.before_input(ctx);
cadcraft_ui_egui::cmdline::capture_tab(ctx, raw);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
cadcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::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).
@@ -197,7 +199,6 @@ 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 {
@@ -301,15 +302,17 @@ 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, 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());
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: cadcraft_ui_egui::framework::apply_frame(viewport, frame),
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()),
// 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,
@@ -387,23 +390,14 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// A refused launch profile ends with a native dialog where a modal renders without the app's run
/// loop (Windows, X11/Wayland), and with the reason on standard error everywhere else: a headless
/// runner must never wait for a modal, and on macOS one opened before the event loop never appears.
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
@@ -550,9 +544,6 @@ 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 +553,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, frame.as_ref())
..window_options(restores_window(persistence_path.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -585,12 +576,22 @@ 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 forced_x11 {
if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On {
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")]
@@ -603,7 +604,6 @@ 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.
@@ -666,7 +666,7 @@ fn main() -> eframe::Result {
}
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
app.integrated_titlebar = cfg!(target_os = "macos");
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -717,6 +717,8 @@ 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,
}))
}),
@@ -754,7 +756,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, None);
let o = window_options(false, STENCIL_BITS);
assert!(o.centered, "centred on launch");
assert!(o.persist_window, "the window state is saved for the next launch");
}
@@ -762,7 +764,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, None);
let o = window_options(true, STENCIL_BITS);
assert!(!o.centered, "centring would move a restored window");
assert!(o.persist_window);
}
@@ -787,8 +789,8 @@ mod tests {
#[test]
fn the_window_carries_the_chosen_stencil_bits() {
for bits in [0, STENCIL_BITS] {
assert_eq!(window_options(false, bits, None).stencil_buffer, bits);
assert_eq!(window_options(true, bits, None).stencil_buffer, bits);
assert_eq!(window_options(false, bits).stencil_buffer, bits);
assert_eq!(window_options(true, bits).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");
@@ -842,17 +844,3 @@ mod tests {
assert_eq!(raw.system_theme, None);
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+2 -10
View File
@@ -15,9 +15,6 @@ 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
@@ -61,6 +58,7 @@ 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"));
@@ -71,8 +69,6 @@ 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));
@@ -89,7 +85,6 @@ impl NativeMenu {
items,
submenus,
predefined,
quit,
language,
last_refresh: f64::NEG_INFINITY,
recent: app.ui.recent_files.clone(),
@@ -119,9 +114,7 @@ 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 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 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 {
@@ -140,7 +133,6 @@ 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));
}
+5 -5
View File
@@ -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, false, permissions).unwrap();
ui.docking.set_visible(Panel::ToolSets, false, None, 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, egui::Rect::from_min_size(egui::pos2(120.0, 90.0), egui::vec2(340.0, 410.0)));
assert_eq!(reloaded.docking.layout.floating[0].rect, [120.0, 90.0, 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();
}
+3
View File
@@ -2,4 +2,7 @@ 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
+3 -4
View File
@@ -238,9 +238,8 @@ mod tests {
assert!(f.t.near(g.t, 1e-3), "{f:?} {g:?}");
assert!((f.k - g.k).abs() < 1e-2, "{f:?} {g:?}");
}
// 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());
// 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());
}
}
+1 -1
View File
@@ -47,7 +47,7 @@ mod proxy;
mod text;
mod wipeout;
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, TagKey, mtext_literal};
pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal};
pub use common::{Common, Handle, Lineweight, RawTag, Transparency};
pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid};
pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader};
-67
View File
@@ -1,6 +1,3 @@
use std::cmp::Ordering;
use std::collections::BTreeMap;
use super::common::{Common, Lineweight};
use super::text::{MText, Text};
use super::{Color, Deserialize, EntityKind, Mat3, Serialize, Vec2, Vec3};
@@ -145,43 +142,6 @@ impl AttribProps {
}
}
/// An attribute tag as attributes are matched to their definitions and to each other: ASCII
/// letters in either case are the same tag, other characters must be equal. As an ordered map key
/// it finds the match in a logarithmic number of comparisons, where comparing each attribute with
/// each definition costs their product on a block with many of both (#1923). It orders, rather
/// than hashes, so the cost doesn't depend on hash keys a crafted file could predict (the web
/// build's `RandomState`), as in the layer and block name index.
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
impl TagKey<'_> {
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
self.0.bytes().map(|b| b.to_ascii_lowercase())
}
}
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(other.0)
}
}
impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.folded().cmp(other.folded())
}
}
impl PartialOrd for TagKey<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Insert {
@@ -244,31 +204,4 @@ impl Insert {
.then_before(Mat3::scale(self.scale.x, self.scale.y))
.then_before(Mat3::translate(-base))
}
/// The reference's attributes by tag: of several with one tag (in any ASCII case), the first.
/// Built once, it tells whether the reference carries a definition's tag, and its value, in
/// one lookup instead of a pass over the attributes per definition (#1923).
pub fn attribs_by_tag(&self) -> BTreeMap<TagKey<'_>, &Attrib> {
let mut by_tag = BTreeMap::new();
for a in &self.attribs {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(a);
}
by_tag
}
}
impl crate::Block {
/// The block's attribute definitions by tag: of several with one tag (in any ASCII case), the
/// first in the block's order, the one an attribute of that tag takes its properties from.
/// Built once for all of a reference's attributes, it matches each in one lookup instead of a
/// pass over the block per attribute (#1923).
pub fn attdefs_by_tag(&self) -> BTreeMap<TagKey<'_>, &crate::Entity> {
let mut by_tag = BTreeMap::new();
for e in self.entities.iter() {
if let EntityKind::AttDef(a) = &e.kind {
by_tag.entry(TagKey(a.tag.as_str())).or_insert(e.as_ref());
}
}
by_tag
}
}
+17 -20
View File
@@ -1,10 +1,10 @@
//! Approximate entity bounds (used for extents, zoom and selection pre-filtering).
use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use cadcraft_geom::{Arc, Bounds2, EPS, Polyline, Vec2, bulge_to_arc};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim, TagKey};
use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
@@ -283,33 +283,33 @@ fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
/// definition's, from the block's definitions by tag `defs` (layer "0" being the insert's).
fn attrib_layer<'a>(defs: Option<&BTreeMap<TagKey<'a>, &'a Entity>>, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| defs.and_then(|defs| defs.get(&TagKey(&a.tag))).map_or("0", |be| be.common.layer.as_str()))
/// definition's (layer "0" being the insert's).
fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str {
a.props.layer.as_deref().unwrap_or_else(|| {
d.block(&ins.block)
.and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag))))
.map_or("0", |be| be.common.layer.as_str())
})
}
/// The bounds of a block's contents, in block coordinates: its geometry, which every reference to
/// the block shows, and the value of each constant attribute definition ATTMODE shows, by tag, which
/// only a block reference draws (a dimension's block does not), and only when the reference
/// carries no attribute of that tag. They are kept apart so that the one cache serves every
/// reference, whichever asks first. Also the block's attribute definitions by tag, for the layer
/// of an attribute that has none of its own.
/// reference, whichever asks first.
struct Contents<'a> {
geometry: Bounds2,
constants: Vec<(&'a str, Bounds2)>,
defs: BTreeMap<TagKey<'a>, &'a Entity>,
}
impl Contents<'_> {
/// What reference `ins` shows of the block: its geometry and the constant values `ins` has
/// no attribute for (that attribute is drawn instead, and counted with the attributes).
fn in_reference(&self, ins: &crate::Insert) -> Bounds2 {
if self.constants.is_empty() {
return self.geometry;
}
// The reference's tags are gathered once, not scanned again for each constant (#1923).
let carried = ins.attribs_by_tag();
self.constants.iter().filter(|(tag, _)| !carried.contains_key(&TagKey(tag))).fold(self.geometry, |b, (_, c)| b.union(c))
self.constants
.iter()
.filter(|(tag, _)| !ins.attribs.iter().any(|r| r.tag.eq_ignore_ascii_case(tag)))
.fold(self.geometry, |b, (_, c)| b.union(c))
}
}
@@ -323,7 +323,7 @@ fn contents<'a, 'm>(
) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) {
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new(), defs: blk.attdefs_by_tag() };
let mut c = Contents { geometry: Bounds2::EMPTY, constants: Vec::new() };
// ATTMODE, as the renderer applies it to a constant value: 0 shows none, 1 the visible
// ones, 2 all of them.
let attmode = d.header.i64("ATTMODE", 1);
@@ -487,12 +487,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// one draws nothing, so it contributes nothing: ZOOM Extents must not fly off to its
// insertion point. Attributes below still count.
let mut b = Bounds2::EMPTY;
let mut defs = None;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs);
let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -514,7 +511,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
+19 -35
View File
@@ -14,7 +14,6 @@ mod format;
mod gdt;
mod header;
pub mod library;
mod names;
mod plotstyle;
mod plotter;
mod raster;
@@ -37,7 +36,6 @@ pub use extents::{
pub use format::Format;
pub use gdt::*;
pub use header::{HVal, Header};
pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
@@ -103,25 +101,19 @@ pub struct Drawing {
pub header: Header,
/// File data CADCraft does not model, written back on save.
pub foreign: std::sync::Arc<foreign::Foreign>,
/// Layers in table order; [`Drawing::layer`] looks them up by name.
pub layers: NamedList<Layer>,
/// 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 layers: Vec<Layer>,
pub linetypes: Vec<Linetype>,
pub text_styles: Vec<TextStyle>,
pub dim_styles: Vec<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
/// Block definitions by name; [`Drawing::block`] looks them up.
pub blocks: NamedMap<std::sync::Arc<Block>>,
pub blocks: BTreeMap<String, std::sync::Arc<Block>>,
pub model: EntityStore,
/// Model layout's page setup, or the default extents-to-fit setup for a new drawing.
pub model_page: Option<PageSetup>,
/// Layouts in list order (`tab_order` orders the tabs); [`Drawing::layout`] looks them up by name.
pub layouts: NamedList<Layout>,
pub layouts: Vec<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>,
@@ -203,22 +195,21 @@ impl Drawing {
Drawing {
header: Header::default(),
foreign: std::sync::Arc::default(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }].into(),
layers: vec![Layer::default(), Layer { name: "Defpoints".into(), plot: false, ..Layer::default() }],
linetypes: vec![
Linetype { name: "ByBlock".into(), description: String::new(), pattern: Vec::new() },
Linetype { name: "ByLayer".into(), description: String::new(), pattern: Vec::new() },
Linetype::continuous(),
]
.into(),
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
],
text_styles: vec![TextStyle::default()],
dim_styles: vec![DimStyle::default()],
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
mline_styles: vec![MLineStyle::default()],
blocks: NamedMap::default(),
blocks: BTreeMap::new(),
model: EntityStore::new(),
model_page: None,
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)].into(),
layouts: vec![Layout::new("Layout1", 1), Layout::new("Layout2", 2)],
active_layout: None,
views: Vec::new(),
vports: Vec::new(),
@@ -322,25 +313,20 @@ impl Drawing {
}
}
/// The first layer named `name`, without case.
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.by_name(name)
self.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first layer named `name`, without case, to change.
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.by_name_mut(name)
self.layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first linetype named `name`, without case.
pub fn linetype(&self, name: &str) -> Option<&Linetype> {
self.linetypes.by_name(name)
self.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first text style named `name`, without case.
pub fn text_style(&self, name: &str) -> Option<&TextStyle> {
self.text_styles.by_name(name)
self.text_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The first dimension style named `name`, without case.
pub fn dim_style(&self, name: &str) -> Option<&DimStyle> {
self.dim_styles.by_name(name)
self.dim_styles.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// The DIM* variables in the header that differ from the current dimension style, as
@@ -408,13 +394,11 @@ impl Drawing {
}
}
}
/// The block named exactly `name`, else the first by name order named `name` without case.
pub fn block(&self, name: &str) -> Option<&std::sync::Arc<Block>> {
self.blocks.by_name(name)
self.blocks.get(name).or_else(|| self.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
}
/// The first layout named `name`, without case.
pub fn layout(&self, name: &str) -> Option<&Layout> {
self.layouts.by_name(name)
self.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(name))
}
/// Add a layer if missing; returns whether it was created.
-575
View File
@@ -1,575 +0,0 @@
//! 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), [`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
//! by those bytes, not hashed: a lookup costs a logarithmic number of name comparisons whatever
//! the names are, also where a file could predict a hash's keys (the web build's `RandomState`).
//! Every change to a table goes through `DerefMut`, which drops the index, so it can never be
//! stale. The index is built only once a table has been scanned [`SCANS_BEFORE_INDEX`] times since
//! it last changed: a table changed between every few hundred lookups costs at most about 2.5 times
//! what scanning it always did, and one looked up many times in between is indexed once.
use std::collections::{BTreeMap, btree_map};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, OnceLock};
/// Tables with fewer entries than this are always scanned: a search of the index costs about what a
/// scan of 100 names does (measured), so a smaller table gains nothing from one.
const MIN_INDEXED: usize = 128;
/// Lookups that scan a table after it changed before its index is built. A build costs about 100
/// to 350 scans (measured on tables of 100 to 40 000 names), so a table changed after every few
/// hundred lookups costs at most about 2.5 times what scanning it always did.
const SCANS_BEFORE_INDEX: u32 = 256;
/// From a name with its ASCII letters lower-cased to the first entry, in table order, of that name.
struct Index<V>(BTreeMap<Box<[u8]>, V>);
impl<V> Index<V> {
fn build<'a>(entries: impl Iterator<Item = (&'a str, V)>) -> Self {
let mut map = BTreeMap::new();
for (name, v) in entries {
map.entry(name.to_ascii_lowercase().into_bytes().into_boxed_slice()).or_insert(v);
}
Index(map)
}
/// The first entry named `name`, without case.
fn get(&self, name: &str) -> Option<&V> {
with_folded(name, |folded| self.0.get(folded))
}
}
/// `f` of the bytes of `name` with its ASCII letters lower-cased, which are equal for the names
/// `eq_ignore_ascii_case` finds equal. A short name is folded on the stack.
fn with_folded<R>(name: &str, f: impl FnOnce(&[u8]) -> R) -> R {
let mut buf = [0u8; 64];
match buf.get_mut(..name.len()) {
Some(short) => {
short.copy_from_slice(name.as_bytes());
short.make_ascii_lowercase();
f(short)
}
None => f(name.to_ascii_lowercase().as_bytes()),
}
}
/// A table's index: built on demand, shared by copies of the unchanged table (an undo snapshot),
/// dropped when the table changes.
struct Lazy<V> {
index: OnceLock<Arc<Index<V>>>,
/// Lookups that scanned the table since it last changed.
scans: AtomicU32,
}
impl<V> Lazy<V> {
/// The index of a table of `len` entries, built with `build` once the table has been scanned
/// often enough since it changed; `None` while it is to be scanned.
fn get(&self, len: usize, build: impl FnOnce() -> Index<V>) -> Option<&Index<V>> {
if let Some(ix) = self.index.get() {
return Some(ix);
}
if len < MIN_INDEXED || self.scans.fetch_add(1, Ordering::Relaxed) < SCANS_BEFORE_INDEX {
return None;
}
Some(self.index.get_or_init(|| Arc::new(build())))
}
/// Forget the index: the table may change.
fn clear(&mut self) {
self.index = OnceLock::new();
*self.scans.get_mut() = 0;
}
}
impl<V> Default for Lazy<V> {
fn default() -> Self {
Lazy { index: OnceLock::new(), scans: AtomicU32::new(0) }
}
}
impl<V> Clone for Lazy<V> {
fn clone(&self) -> Self {
Lazy { index: self.index.clone(), scans: AtomicU32::new(0) }
}
}
/// An entry of a [`NamedList`]: what it is looked up by.
pub trait Named {
fn name(&self) -> &str;
}
/// 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, 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>,
}
impl<T: Named> NamedList<T> {
/// The position of the first entry named `name`, without case.
pub fn position_by_name(&self, name: &str) -> Option<usize> {
match self.index.get(self.list.len(), || Index::build(self.list.iter().enumerate().map(|(i, t)| (t.name(), i)))) {
Some(ix) => ix.get(name).copied(),
None => self.list.iter().position(|t| t.name().eq_ignore_ascii_case(name)),
}
}
/// The first entry named `name`, without case.
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> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.list
}
}
impl<T> DerefMut for NamedList<T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
self.index.clear();
&mut self.list
}
}
impl<T> Default for NamedList<T> {
fn default() -> Self {
Vec::new().into()
}
}
impl<T: Clone> Clone for NamedList<T> {
fn clone(&self) -> Self {
NamedList { list: self.list.clone(), index: self.index.clone() }
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for NamedList<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.list.fmt(f)
}
}
impl<T: PartialEq> PartialEq for NamedList<T> {
fn eq(&self, other: &Self) -> bool {
self.list == other.list
}
}
impl<T> From<Vec<T>> for NamedList<T> {
fn from(list: Vec<T>) -> Self {
NamedList { list, index: Lazy::default() }
}
}
impl<T> From<NamedList<T>> for Vec<T> {
fn from(l: NamedList<T>) -> Self {
l.list
}
}
impl<T: serde::Serialize> serde::Serialize for NamedList<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.list.serialize(s)
}
}
impl<T> FromIterator<T> for NamedList<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Vec::from_iter(iter).into()
}
}
impl<T> IntoIterator for NamedList<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.list.into_iter()
}
}
impl<'a, T> IntoIterator for &'a NamedList<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.list.iter()
}
}
impl<'a, T> IntoIterator for &'a mut NamedList<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
/// Entries by name, in name order (the drawing's block definitions). It reads and changes as a
/// `BTreeMap`; [`NamedMap::by_name`] finds an entry by its exact name, else the first in name
/// order whose name matches without case.
pub struct NamedMap<V> {
map: BTreeMap<String, V>,
index: Lazy<Box<str>>,
}
impl<V> NamedMap<V> {
/// The entry named exactly `name`, else the first in name order named `name` without case.
pub fn by_name(&self, name: &str) -> Option<&V> {
if let Some(v) = self.map.get(name) {
return Some(v);
}
match self.index.get(self.map.len(), || Index::build(self.map.keys().map(|k| (k.as_str(), Box::from(k.as_str()))))) {
Some(ix) => ix.get(name).and_then(|k| self.map.get(&**k)),
None => self.map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v),
}
}
}
impl<V> Deref for NamedMap<V> {
type Target = BTreeMap<String, V>;
fn deref(&self) -> &BTreeMap<String, V> {
&self.map
}
}
impl<V> DerefMut for NamedMap<V> {
fn deref_mut(&mut self) -> &mut BTreeMap<String, V> {
self.index.clear();
&mut self.map
}
}
impl<V> Default for NamedMap<V> {
fn default() -> Self {
BTreeMap::new().into()
}
}
impl<V: Clone> Clone for NamedMap<V> {
fn clone(&self) -> Self {
NamedMap { map: self.map.clone(), index: self.index.clone() }
}
}
impl<V: std::fmt::Debug> std::fmt::Debug for NamedMap<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.map.fmt(f)
}
}
impl<V: PartialEq> PartialEq for NamedMap<V> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
impl<V> From<BTreeMap<String, V>> for NamedMap<V> {
fn from(map: BTreeMap<String, V>) -> Self {
NamedMap { map, index: Lazy::default() }
}
}
impl<V> FromIterator<(String, V)> for NamedMap<V> {
fn from_iter<I: IntoIterator<Item = (String, V)>>(iter: I) -> Self {
BTreeMap::from_iter(iter).into()
}
}
impl<V> IntoIterator for NamedMap<V> {
type Item = (String, V);
type IntoIter = btree_map::IntoIter<String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a, V> IntoIterator for &'a NamedMap<V> {
type Item = (&'a String, &'a V);
type IntoIter = btree_map::Iter<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<'a, V> IntoIterator for &'a mut NamedMap<V> {
type Item = (&'a String, &'a mut V);
type IntoIter = btree_map::IterMut<'a, String, V>;
fn into_iter(self) -> Self::IntoIter {
self.deref_mut().iter_mut()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
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).
fn probes<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
names.flat_map(|n| [n.to_string(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]).collect()
}
fn layers_indexed(d: &Drawing) -> bool {
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()
}
/// `layer_mut` finds the first layer of a name and drops the index, as the table may change
/// through it. Then every layer lookup finds what a scan in table order finds (the first of a
/// name without case), and a large table looked up this often is left indexed.
fn check_layers(d: &mut Drawing, extra: &[&str]) {
let p = extra.first().copied().unwrap_or("L1");
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(p)).and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer_mut(p).map(|l| std::ptr::from_ref(&*l)), want, "{p}");
assert!(want.is_none() || !layers_indexed(d));
let names: Vec<String> = d.layers.iter().map(|l| l.name.clone()).collect();
for p in probes(names.iter().map(String::as_str).chain(extra.iter().copied())) {
let want = d.layers.iter().position(|l| l.name.eq_ignore_ascii_case(&p));
assert_eq!(d.layers.position_by_name(&p), want, "{p}");
let at = want.and_then(|i| d.layers.get(i)).map(std::ptr::from_ref);
assert_eq!(d.layer(&p).map(std::ptr::from_ref), at, "{p}");
}
assert_eq!(layers_indexed(d), d.layers.len() >= MIN_INDEXED);
}
/// Every block lookup finds what `Drawing::block` always found: the block of that exact name,
/// else the first in name order of that name without case. Only names that miss an exact name
/// count towards building the index, so the names are looked up twice.
fn check_blocks(d: &Drawing, extra: &[&str]) {
let names: Vec<String> = d.blocks.keys().cloned().collect();
for p in probes(names.iter().chain(&names).map(String::as_str).chain(extra.iter().copied())) {
let want = d.blocks.get(&p).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(&p)).map(|(_, v)| v));
assert_eq!(d.block(&p).map(std::ptr::from_ref), want.map(std::ptr::from_ref), "{p}");
}
assert_eq!(blocks_indexed(d), d.blocks.len() >= MIN_INDEXED);
}
/// The index answers by itself, with no scan to fall back on: every name finds the first entry
/// of its name without case, also names that differ only after a long shared prefix, names
/// that fill the stack buffer or are longer, and names with non-ASCII letters (which keep their
/// case). Names are compared, not hashed, so no two names can share a slot.
#[test]
fn the_index_alone_finds_the_first_entry_of_every_name() {
let long = "x".repeat(100);
let names: Vec<String> = vec![
"Door".into(),
"DOOR".into(),
"door2".into(),
format!("{long}A"),
format!("{long}a"),
format!("{long}B"),
format!("{}b", "P".repeat(63)),
format!("{}B", "p".repeat(63)),
"Ärea".into(),
"ärea".into(),
"ÄREA".into(),
String::new(),
];
let ix = super::Index::build(names.iter().enumerate().map(|(i, n)| (n.as_str(), i)));
for p in names.iter().flat_map(|n| [n.clone(), n.to_ascii_uppercase(), n.to_ascii_lowercase(), format!("{n}?")]) {
let want = names.iter().position(|n| n.eq_ignore_ascii_case(&p));
assert_eq!(ix.get(&p).copied(), want, "{p:?}");
}
assert_eq!(ix.get(&format!("{long}a")), Some(&3));
assert_eq!(ix.get("ärea"), Some(&9));
}
#[test]
fn layer_lookups_find_the_first_of_a_name_through_every_change() {
let mut d = Drawing::new_imperial();
d.layers = (0..200).map(|i| Layer::new(&format!("L{i}"))).chain([Layer::new("l5"), Layer::new("Doors")]).collect();
check_layers(&mut d, &["l5", "missing"]);
// Renamed through layer_mut (RENAME).
d.layer_mut("l7").unwrap().name = "Seven".into();
assert!(!layers_indexed(&d));
assert!(d.layer("L7").is_none());
check_layers(&mut d, &["SEVEN", "L7"]);
// Added (LAYER New, or a file's later record of a name it already has).
d.layers.push(Layer::new("SEVEN"));
assert!(!layers_indexed(&d));
check_layers(&mut d, &["seven"]);
// Removed (PURGE, LAYDEL): the later `l5` becomes the first of that name.
d.layers.retain(|l| l.name != "L5");
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L5").map(|l| l.name.as_str()), Some("l5"));
check_layers(&mut d, &["L5"]);
// Inserted before an earlier layer of the same name.
d.layers.insert(0, Layer::new("l9"));
assert!(!layers_indexed(&d));
assert_eq!(d.layer("L9").map(|l| l.name.as_str()), Some("l9"));
check_layers(&mut d, &["L9"]);
// Changed by position, and by a loop over all of them.
d.layers[3].name = "Third".into();
assert!(!layers_indexed(&d));
check_layers(&mut d, &["third"]);
for l in &mut d.layers {
l.name.make_ascii_uppercase();
}
assert!(!layers_indexed(&d));
check_layers(&mut d, &["doors"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let names = |d: &Drawing| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
assert!(layers_indexed(&d));
let (snap, before) = (d.clone(), names(&d));
d.layers.clear();
d.layers.push(Layer::new("Only"));
check_layers(&mut d, &["only", "L1"]);
d = snap;
assert!(layers_indexed(&d));
assert_eq!(names(&d), before);
check_layers(&mut d, &["THIRD"]);
// The whole table replaced (LAYERP, LAYUNISO).
d.layers = vec![Layer::new("0"), Layer::new("A"), Layer::new("a")].into();
check_layers(&mut d, &["a"]);
}
#[test]
fn block_lookups_find_an_exact_name_else_the_first_without_case_through_every_change() {
let block = |name: &str| Arc::new(Block::new(name));
let mut d = Drawing::new_imperial();
for name in (0..150).map(|i| format!("B{i}")).chain(["Door", "DOOR", "door"].map(String::from)) {
d.blocks.insert(name.clone(), block(&name));
}
check_blocks(&d, &["dOOR", "missing"]);
// An exact name wins; otherwise the first in name order ("DOOR" < "Door" < "door").
assert_eq!(d.block("door").map(|b| b.name.as_str()), Some("door"));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DOOR"));
// Removed (PURGE, a definition replaced under another name).
d.blocks.remove("DOOR");
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("Door"));
check_blocks(&d, &["dOOR"]);
// Added before the first of that name.
d.blocks.insert("DoOr".into(), block("DoOr"));
assert!(!blocks_indexed(&d));
assert_eq!(d.block("dOOR").map(|b| b.name.as_str()), Some("DoOr"));
check_blocks(&d, &["dOOR"]);
// Renamed (RENAME takes the definition out and puts it back under the new name).
let b1 = d.blocks.remove("B1").unwrap();
d.blocks.insert("Renamed".into(), b1);
assert!(d.block("b1").is_none() && d.block("RENAMED").is_some());
check_blocks(&d, &["b1", "RENAMED"]);
// Redefined in place, and changed through get_mut: the names stay.
d.blocks.insert("Door".into(), block("Door"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["DOOR"]);
Arc::make_mut(d.blocks.get_mut("B2").unwrap()).description = "changed".into();
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b2"]);
// Many removed at once.
d.blocks.retain(|k, _| !k.starts_with("B9"));
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b9", "b90"]);
// A loop over all of them.
for (_, b) in &mut d.blocks {
Arc::make_mut(b).description = "looped".into();
}
assert!(!blocks_indexed(&d));
check_blocks(&d, &["b3"]);
// Undo: a snapshot keeps the table it was taken with, and its index.
let snap = d.clone();
d.blocks.clear();
d.blocks.insert("Only".into(), block("Only"));
check_blocks(&d, &["only", "door"]);
d = snap;
assert!(blocks_indexed(&d));
check_blocks(&d, &["DOOR", "only"]);
}
}
+2 -2
View File
@@ -1018,8 +1018,8 @@ impl LayerState {
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: impl Into<Vec<Layer>>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers: layers.into(), current: current.into(), ..LayerState::default() }
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
}
}
-155
View File
@@ -890,158 +890,3 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(1, true) < 40.0);
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
}
#[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
// attribute without a layer of its own (in a third case) lies on the first one's.
let top = |defs: [(&str, &str); 2]| {
let mut d = Drawing::new_imperial();
let mut frozen = Layer::new("AFRZ");
frozen.frozen = true;
d.layers.push(frozen);
let mut blk = Block::new("B");
blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1));
for (h, (layer, tag)) in (2..).zip(defs) {
blk.entities.push(on_layer(layer, EntityKind::AttDef(plain_attrib(tag)), h));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
let mut a = plain_attrib("Tag");
a.text.insert = Vec3::new(0.0, 500.0, 0.0);
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1.y
};
assert!(top([("AFRZ", "TAG"), ("0", "tag")]) < 100.0, "on the first definition's frozen layer");
assert!(top([("0", "tag"), ("AFRZ", "TAG")]) > 400.0, "on the first definition's layer 0");
}
#[test]
fn constant_definitions_of_one_tag_all_count_unless_the_reference_carries_the_tag() {
// Two constant definitions of one tag, in different case: a reference draws both values,
// unless it carries an attribute of that tag (in a third case), which stands for both.
let max = |attribs: Vec<Attrib>| {
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, tag, at) in [(2, "C", Vec3::new(0.0, 5000.0, 0.0)), (3, "c", Vec3::new(7000.0, 0.0, 0.0))] {
let mut a = plain_attrib(tag);
a.text.insert = at;
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = attribs;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
extents_pair(&d).1
};
for shown in [max(vec![]), max(vec![plain_attrib("D")])] {
assert!(shown.x > 6000.0 && shown.y > 4000.0, "both values count: {shown:?}");
}
let carried = max(vec![plain_attrib("D"), plain_attrib("Cc"), plain_attrib("C")]);
assert!(carried.x < 100.0 && carried.y < 100.0, "neither value counts: {carried:?}");
}
#[test]
fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
// #1923: one reference with N attributes (none with a layer of its own) of a block with N
// constant definitions, the tags N long ones alike up to their last characters, no attribute's
// a definition's. Comparing each attribute with each definition, for its layer and for which
// constant values the reference carries, cost N x N comparisons of whole tags (many seconds
// here); one lookup per attribute or definition costs milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let mut d = Drawing::new_imperial();
let mut blk = Block::new("B");
blk.entities.push(Entity::new(Handle(1), line((0.0, 0.0), (1.0, 1.0))));
for (h, i) in (2..).zip(0..N) {
let mut a = plain_attrib(&tag('D', i));
a.constant = true;
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(a)));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
/// blocks and N references to blocks it does not have, opened in N² name comparisons (#1924).
#[test]
fn layer_and_block_lookups_by_name_cost_about_the_same_for_any_table_size() {
const N: usize = 60_000;
let mut d = Drawing::new_imperial();
d.layers = (0..N).map(|i| Layer::new(&format!("L{i}"))).collect();
for i in 0..N {
let name = format!("B{i}");
d.blocks.insert(name.clone(), std::sync::Arc::new(Block::new(&name)));
}
let started = std::time::Instant::now();
for i in 0..N {
assert!(d.layer(&format!("l{i}")).is_some() && d.layer(&format!("M{i}")).is_none());
assert!(d.block(&format!("b{i}")).is_some() && d.block(&format!("Z{i}")).is_none());
}
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 -7
View File
@@ -1,5 +1,5 @@
//! Dimensions and leaders: DIMLINEAR, DIMALIGNED, DIMRADIUS, DIMDIAMETER, DIMANGULAR, DIMARC,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, QLEADER, DIMOVERRIDE,
//! DIMORDINATE, DIMCONTINUE, DIMBASELINE, QDIM, DIM (smart), MLEADER, LEADER, DIMOVERRIDE,
//! DIMREASSOCIATE / DIMDISASSOCIATE, DIMTEDIT, DIMSPACE; DIMEDIT, DIMJOGGED, DIMJOGLINE,
//! DIMBREAK and DIMINSPECT in `annotate_dimedit.rs`.
@@ -19,7 +19,6 @@ mod edit;
mod leader;
mod linear;
mod mleader;
mod qleader;
mod radial;
use angular::{AngularM, ArcLenM, run_angular, run_arclen};
@@ -28,7 +27,6 @@ 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> {
@@ -95,10 +93,6 @@ 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?}")
+3 -25
View File
@@ -42,13 +42,8 @@ pub(super) struct LeaderM {
}
/// What follows the leader.
pub(super) enum Annotation {
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,
@@ -268,13 +263,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.
pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result<Vec<Handle>> {
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::Quick { .. } | Annotation::Copy(_) = ann {
if let Annotation::Text(_) | 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.
@@ -315,23 +310,6 @@ pub(super) fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: boo
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 };
-121
View File
@@ -1,121 +0,0 @@
//! 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<_>>() }))
}
+5 -7
View File
@@ -386,18 +386,16 @@ fn fmt(v: f64) -> String {
format!("{v:.4}")
}
/// 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).
/// A count typed at a prompt (Enter keeps `cur`); `None` for inputs the prompt ignores.
fn count(i: &Input, cur: u64, max: u64) -> Result<Option<u64>> {
match i {
Input::Enter => Ok(Some(cur)),
Input::Text(t) => t
.trim()
.parse::<u64>()
.parse::<f64>()
.ok()
.filter(|v| (1..=max).contains(v))
.map(Some)
.filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= max as f64)
.map(|v| Some(v as u64))
.ok_or_else(|| other(format!("Requires an integer between 1 and {max} (MAXARRAY limits the size of the array)."))),
_ => Ok(None),
}
@@ -439,7 +437,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.
pub(crate) fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result<u64> {
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"))),
+59 -182
View File
@@ -403,14 +403,13 @@ 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_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (1..=Grid::MAX).contains(n))
.as_f64()
.filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX))
.map(|n| n as u32)
.ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))),
}
};
@@ -834,35 +833,11 @@ 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,
@@ -1043,66 +1018,6 @@ 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.
@@ -1110,14 +1025,8 @@ fn distance(t: &str) -> Result<f64> {
number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".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)
fn nonzero(t: &str) -> Result<f64> {
number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into()))
}
impl Interactive for InsertM {
@@ -1138,31 +1047,22 @@ 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),
// 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::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"),
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::POINT_OR_NUMBER).default("use X scale factor").base(at),
InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"),
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::POINT_OR_NUMBER),
InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::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);
@@ -1238,58 +1138,45 @@ impl Interactive for InsertM {
self.stage = InsStage::Point;
}
}
// 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())),
};
}
// 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())),
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
};
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.
InsStage::PresetAxis(ax) => {
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())),
let f = match i {
Input::Text(t) => nonzero(&t)?,
Input::Enter => 1.0,
_ => return Ok(Step::Continue),
};
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 => {
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())),
};
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;
}
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,
@@ -1298,7 +1185,7 @@ impl Interactive for InsertM {
return self.corner_scale(s, sc);
}
Input::Text(t) => {
self.x_scale = Some(nonzero(&t, "Requires a non-zero number.")?);
self.x_scale = Some(nonzero(&t)?);
self.stage = InsStage::YScale;
}
Input::Enter => {
@@ -1315,11 +1202,10 @@ 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, NUMERIC)?,
Input::Text(t) => nonzero(&t)?,
Input::Enter => x,
_ => return Err(EngineError::Other(NUMERIC.into())),
_ => return Ok(Step::Continue),
};
self.scale = Some(Vec2::new(x, y));
if self.xyz {
@@ -1328,15 +1214,11 @@ 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, SECOND_POINT)?,
Input::Text(t) => nonzero(&t)?,
Input::Enter => self.x_scale.unwrap_or(1.0).abs(),
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 Ok(Step::Continue),
});
return self.advance(s);
}
@@ -1350,14 +1232,17 @@ 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::<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)))?;
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),
};
if self.stage == InsStage::Rows {
self.rows = Some(n);
} else {
@@ -1379,19 +1264,11 @@ impl Interactive for InsertM {
return self.advance(s);
}
}
// A distance, or two points (AutoCAD 2024, measured): Enter is refused too.
InsStage::ColSpacing => {
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())),
};
if let Input::Text(t) = i {
self.col_spacing = Some(distance(&t)?);
return self.advance(s);
}
}
InsStage::Attribs => {
let (tag, _, default, _) = self.attdefs.get(self.asked).cloned().unwrap_or_default();
+7 -4
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert, TagKey};
use cadcraft_doc::{Attrib, Block, Entity, EntityKind, Handle, Insert};
use serde_json::{Value, json};
use crate::cmd::curves::KW;
@@ -102,14 +102,17 @@ impl Interactive for AttdispM {
/// Properties set on single attributes (layer, colour, …) go back to the definitions', as in AutoCAD.
pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib> {
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
t.value = ins
.attribs
.iter()
.find(|a| a.tag.eq_ignore_ascii_case(&ad.tag))
.map(|a| a.text.value.clone())
.unwrap_or_else(|| ad.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
+8 -8
View File
@@ -2,7 +2,7 @@
//! become text with the values they show instead of the block's attribute definitions.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, TagKey};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Insert};
use serde_json::{Value, json};
use crate::cmd::machines::SelectRun;
@@ -28,22 +28,22 @@ fn run_burst(s: &mut Session, p: &Value) -> Result<Value> {
fn burst_pieces(d: &Drawing, e: &Entity) -> Option<Vec<Entity>> {
let EntityKind::Insert(ins) = &e.kind else { return None };
let mut out: Vec<Entity> = explode_kind(d, e)?.into_iter().filter(|p| !matches!(p.kind, EntityKind::AttDef(_))).collect();
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&ins.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for a in ins.attribs.iter().filter(|a| !a.invisible) {
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
out.push(Entity { handle: Handle(0), common: attrib_common(e, defs.get(&TagKey(&a.tag)).copied(), &a.props), kind });
out.push(Entity { handle: Handle(0), common: attrib_common(d, e, ins, &a.tag, &a.props), kind });
}
Some(out)
}
/// The properties an attribute is drawn with: its own, else those of its definition `def`; layer
/// 0 is the reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the
/// block's objects.
fn attrib_common(e: &Entity, def: Option<&Entity>, props: &cadcraft_doc::AttribProps) -> Common {
/// The properties an attribute is drawn with: its own, else its definition's; layer 0 is the
/// reference's layer and ByBlock colour the reference's colour, as EXPLODE gives the block's
/// objects.
fn attrib_common(d: &Drawing, e: &Entity, ins: &Insert, tag: &str, props: &cadcraft_doc::AttribProps) -> Common {
let def =
d.block(&ins.block).and_then(|b| b.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(tag))));
// An attribute without a definition follows the reference.
let base = def.map(|de| de.common.clone()).unwrap_or_else(|| Common { color: Color::ByBlock, ..Common::default() });
let mut c = props.over(&base);
+5 -52
View File
@@ -5,7 +5,7 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, TagKey, Transparency};
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Lineweight, Transparency};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
@@ -111,10 +111,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
.collect();
// An attribute draws with its definition's properties, except those set on it.
let by_block = Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..r.clone() };
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = b.attdefs_by_tag();
out.extend(ins.attribs.iter().filter(|a| !a.invisible).map(|a| {
let def = defs.get(&TagKey(&a.tag)).map(|e| &e.common);
let def = b.entities.iter().find_map(|e| match &e.kind {
EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag) => Some(&e.common),
_ => None,
});
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
@@ -247,51 +248,3 @@ impl Session {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn many_attributes_are_previewed_without_comparing_every_pair_with_the_definitions() {
// #1923: a reference with N attributes of a block with N definitions, the tags N long ones
// alike up to their last characters, no attribute's a definition's. Looking for each
// attribute's definition by comparing it with every one cost N x N comparisons of whole
// tags for each preview (many seconds here); the definitions gathered by tag once cost
// milliseconds.
const N: usize = 4000;
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let attrib = |tag: String| cadcraft_doc::Attrib {
tag,
text: cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "v".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
},
invisible: false,
constant: false,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
let mut d = Drawing::new_metric();
let mut blk = cadcraft_doc::Block::new("B");
for (h, i) in (1..).zip(0..N) {
blk.entities.push(Entity::new(Handle(h), EntityKind::AttDef(attrib(tag('D', i)))));
}
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let ins = cadcraft_doc::Insert { block: "B".into(), attribs: (0..N).map(|i| attrib(tag('A', i))).collect(), ..Default::default() };
let h = d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let t = std::time::Instant::now();
assert_eq!(drawn(&d, h).len(), N);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
}
+15 -24
View File
@@ -8,9 +8,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::super::curves::KW;
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::file::{Version, lost_message, lost_writing, new_folder, own_version, 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};
@@ -48,7 +46,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, notes) = match str_param(p, "name") {
let (entities, bytes, lost, version) = 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)))?,
@@ -56,7 +54,6 @@ 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)
}
@@ -67,7 +64,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, notes) = match str_param(p, "name") {
let (entities, bytes, lost, version) = match str_param(p, "name") {
Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?,
None => {
let hs = targets(s, p)?;
@@ -83,17 +80,16 @@ 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), 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>)> {
/// 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)> {
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.
@@ -119,19 +115,14 @@ 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);
let notes = if drops_unknown(path) { dwg_notes(&d) } else { Vec::new() };
Ok((d.model.len(), bytes.len(), lost, version, notes))
Ok((d.model.len(), bytes.len(), lost, version))
}
/// 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>) {
/// 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>) {
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
@@ -350,7 +341,7 @@ impl DashWblockM {
fn write(&self, s: &mut Session, what: Source) -> Result<Step> {
match write(s, "-wblock", &self.path, what) {
Ok((.., lost, version, notes)) => echo_not_saved(s, &self.path, version, &lost, notes),
Ok((.., lost, version)) => echo_not_saved(s, &self.path, version, &lost),
Err(e) => s.echo(e.to_string()),
}
Ok(Step::Done)
@@ -361,8 +352,8 @@ impl DashWblockM {
return Ok(Step::Done);
}
match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) {
Ok((.., lost, version, notes)) => {
echo_not_saved(s, &self.path, version, &lost, notes);
Ok((.., lost, version)) => {
echo_not_saved(s, &self.path, version, &lost);
erase(s, hs)?;
}
Err(e) => s.echo(e.to_string()),
+4 -4
View File
@@ -265,10 +265,10 @@ 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).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.layers = pick(&src.layers, &used.layers, |l| &l.name);
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.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();
+1 -1
View File
@@ -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.by_name_mut(&name) {
let name = match d.dim_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(existing) if replace => {
let kept = existing.name.clone();
*existing = DimStyle { name: kept.clone(), ..st };
+2 -2
View File
@@ -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? (default PLINEWID unless vertices give widths)}")
.params("{vertices: [[x,y] | {p:[x,y], bulge, startWidth, endWidth}], closed?, width?}")
.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 (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)}")
.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)}")
.interactive(|_| Ok(Box::new(super::draw2::RectM2::default()))),
CommandSpec::new("polygon", "Polygon", run_polygon)
.menu(&["Draw", "Polygon"])
+3 -21
View File
@@ -45,21 +45,15 @@ 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() {
vertex_widths |= size_param("pline", v, "startWidth", true)?.is_some() | size_param("pline", v, "endWidth", true)?.is_some();
size_param("pline", v, "startWidth", true)?;
size_param("pline", v, "endWidth", true)?;
}
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"));
}
// 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 width = size_param("pline", p, "width", true)?.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;
@@ -272,11 +266,8 @@ 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 {
@@ -325,11 +316,6 @@ 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)) {
@@ -393,10 +379,6 @@ 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)
}
+1 -7
View File
@@ -125,11 +125,7 @@ impl Interactive for SplineM {
}
match i {
Input::Point(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);
}
self.pts.push(p);
Ok(Step::Continue)
}
Input::Keyword(k) if k == "Undo" => {
@@ -179,8 +175,6 @@ 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 {
+1 -1
View File
@@ -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_corners_fit, rect_vertices, rect_with_corners, v3};
use super::helpers::{arc, circle, line, lwpoly, 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};
+14 -33
View File
@@ -139,15 +139,6 @@ 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 {
@@ -196,37 +187,27 @@ impl Interactive for DivideM {
self.phase = DivPhase::Value;
Ok(Step::Continue)
}
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) if self.measure => {
(DivPhase::Value, inp @ (Input::Text(_) | Input::Point(_))) => {
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 = self.params(h, pick);
params["length"] = json!(v);
run_measure(s, &params)?;
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,
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, &params)?;
} 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, &params)?;
}
.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, &params)?;
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Cancel),
+16 -42
View File
@@ -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_corners_fit, rect_with_corners, size_param,
number, other, point_param, point_req, rect_with_corners, size_param,
};
use crate::last_used::RectangModes;
@@ -19,30 +19,9 @@ 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, fillet: f64, chamfer: (f64, f64)) -> Result<(f64, f64)> {
fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool) -> 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]"))?;
@@ -59,8 +38,8 @@ fn rect_size(p: &Value, a: Vec2, rot: f64, centered: bool, fillet: f64, chamfer:
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 => area_sides(area, l, false, fillet, chamfer),
(_, Some(b)) if b.is_finite() && b > 0.0 => area_sides(area, b, true, fillet, chamfer),
(Some(l), _) if l.is_finite() && l > 0.0 => (l, area / l),
(_, Some(b)) if b.is_finite() && b > 0.0 => (area / b, b),
_ => return Err(bad("rectang", "area needs `length` or `breadth`")),
}
} else {
@@ -89,7 +68,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, fillet, ch)?;
let (w, h) = rect_size(p, a, rot, centered)?;
if w.abs() < 1e-12 || h.abs() < 1e-12 || !w.is_finite() || !h.is_finite() {
return Err(bad("rectang", "rectangle has no area"));
}
@@ -137,13 +116,10 @@ pub(crate) struct RectM2 {
asking: Option<RAsk>,
}
/// 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)
/// 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 }
}
/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current
@@ -168,10 +144,9 @@ fn modes_line(s: &Session, m: &RectangModes) -> Option<String> {
if m.width > 0.0 {
parts.push(format!("Width={}", d(m.width)));
}
// 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)));
let rot = rotation_text(m.rotation);
if rot != "0.00" {
parts.push(format!("Rotation={rot}"));
}
(!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" ")))
}
@@ -244,7 +219,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 {
@@ -262,7 +237,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(s, self.rotation))
.default(rotation_text(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),
@@ -324,7 +299,7 @@ impl Interactive for RectM2 {
self.asking = Some(a);
return Err(other("Value must be positive."));
}
let (w, h) = area_sides(self.area, v, a == RAsk::AreaWidth, self.fillet, self.chamfer);
let (w, h) = if a == RAsk::AreaLength { (v, self.area / v) } else { (self.area / v, v) };
return self.make(s, w, h);
}
RAsk::DimL => {
@@ -339,8 +314,7 @@ 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),
// 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."))?,
Input::Text(t) => self.rotation = s.angle_settings().direction(&t).ok_or_else(|| other("Requires a valid angle."))?,
_ => {}
},
RAsk::RotPick1 => {
+5 -251
View File
@@ -729,57 +729,6 @@ 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]
@@ -1152,198 +1101,6 @@ 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.
@@ -1379,7 +1136,7 @@ fn rectang_center_mode_json() {
}
/// Guards that fillet, chamfer, width and thickness still apply in centre mode, and that an
/// oversized fillet leaves sharp corners without moving the rectangle off centre.
/// oversized fillet falls back to sharp corners without moving the rectangle off centre.
#[test]
fn rectang_center_mode_honours_options() {
let mut s = Session::new();
@@ -1396,11 +1153,9 @@ 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 leaves sharp corners, each one two coincident vertices
// as in AutoCAD, still centred.
// A fillet too large for the rectangle falls back to sharp corners, still centred.
s.execute("rectang", &json!({"center": true, "p1": [10, 10], "p2": [14, 16], "fillet": 5})).unwrap();
let pts = rect_pts(&s);
assert!(pts.len() == 8 && pts.chunks(2).all(|c| c[0] == c[1]), "{pts:?}");
assert_eq!(rect_pts(&s).len(), 4);
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:?}");
}
@@ -1428,9 +1183,8 @@ 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 (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();
// Area too: the rectangle of that area is centred on the first point.
s.cmdline("rectang 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:?}");
-36
View File
@@ -104,36 +104,6 @@ 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 &notes {
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> {
@@ -903,8 +873,6 @@ 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);
@@ -1037,9 +1005,7 @@ 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`),
@@ -1146,8 +1112,6 @@ 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);
+8 -2
View File
@@ -455,9 +455,15 @@ 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_style(name)?.clone();
let st = d.dim_styles.iter().find(|s| s.name.eq_ignore_ascii_case(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_style(n).is_some());
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)),
);
d.dim_styles.push(DimStyle {
name: new.clone(),
dim_line_color: Color::ByBlock,
+6 -4
View File
@@ -253,14 +253,16 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = base_point(s, "grip.scale", p, &hs)?;
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
let f = base.dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
}
};
apply(s, &hs, &m, bool_or(p, "copy", false))
let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+48 -19
View File
@@ -14,7 +14,7 @@ use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips;
use super::helpers::line;
use super::machines::number;
use super::modify::transform_entities;
use super::modify::{at_elevation, scale_entities, transform_entities};
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -220,14 +220,7 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -240,6 +233,27 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -286,12 +300,20 @@ impl GripEdit {
Ok(Step::Continue)
}
Input::Point(p) => {
let m = self.matrix(p);
self.edit(s, p, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
}
Input::Deferred(d) => {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -300,7 +322,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
self.edit_scale(s, f)
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -327,14 +349,21 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
+14 -33
View File
@@ -68,48 +68,29 @@ 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 too large for the shorter side leaves the corners square, each as two coincident
/// vertices, as AutoCAD stores them.
/// chamfer that doesn't fit leaves the corners square.
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 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 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 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 };
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.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge));
out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out));
}
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.
+2 -1
View File
@@ -62,7 +62,8 @@ impl Scope {
Some(_) => {
let name = given.unwrap_or_default();
let d = s.doc()?;
let l = d.layout(&name).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
let l =
d.layouts.iter().find(|l| l.name.eq_ignore_ascii_case(&name)).ok_or_else(|| bad(cmd, format!("no layout named \"{name}\"")))?;
Ok(Scope::Space(Space::Paper(l.name.clone())))
}
}
+2 -2
View File
@@ -297,7 +297,7 @@ fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYERP", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
d.layers = layers.into();
d.layers = layers;
Ok(json!({"message": "Restored previous layer states."}))
}
@@ -375,7 +375,7 @@ fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
let d = s.doc_mut()?;
let snap = d.header.str("CADCRAFT_LAYISO", "");
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
d.layers = layers.into();
d.layers = layers;
ok()
}
+1 -1
View File
@@ -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?, warnings?}")
.params("{name?: layout (default: the current layout, else the first tab), path: .dwt (or .dwg, .dxf; no extension adds .dwt)} → {name, path, bytes, notSaved?}")
.noundo(),
CommandSpec::new("mview", "Viewports", run_mview)
.alias(&["mv"])
+1 -4
View File
@@ -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, dwg_notes, io, not_saved, not_saved_message, report_dwg_notes};
use super::super::file::{drops_unknown, io, not_saved, not_saved_message};
use super::super::{bad, str_param};
use super::layout_name;
use super::prompts::current_layout;
@@ -136,9 +136,6 @@ 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)
}
+1 -1
View File
@@ -36,7 +36,7 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
+50 -376
View File
@@ -129,406 +129,80 @@ 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()?;
// 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;
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;
for h in hs {
let Some(e) = d.entity(*h) else { continue };
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));
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()),
_ => {}
}
owners.resize(segs.len(), *h);
}
if units.iter().map(|u| u.1.len()).sum::<usize>() < 2 {
if segs.len() < 2 {
return Err(EngineError::Other("Select at least two objects to join.".into()));
}
// 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());
// Chain greedily from the first segment.
let mut chain = vec![segs.remove(0)];
let mut used = vec![owners.remove(0)];
let tol = 1e-6;
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 {
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 {
return Err(EngineError::Other("Objects are not connected.".into()));
}
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
let closed = chain.first().zip(chain.last()).is_some_and(|(a, b)| a.start().near(b.end(), tol));
let mut vs: Vec<PolyVertex> = chain
.iter()
.map(|l| {
let (start_width, end_width) = l.widths.unwrap_or_default();
PolyVertex { p: l.ends.0, bulge: l.bulge, start_width, end_width }
.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()
})
.collect();
if !closed && let Some(l) = links.last() {
vs.push(PolyVertex::new(l.ends.1));
if !closed && let Some(l) = chain.last() {
vs.push(PolyVertex::new(l.end()));
}
// 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 space = s.space();
let doc = s.doc_mut()?;
// 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)) {
for h in hs.iter().filter(|h| used.contains(*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, kind });
st.push(Entity { handle: nh, common: common.unwrap_or_default(), kind: lwpoly(vs, closed) });
}
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) {
+96 -237
View File
@@ -1,4 +1,4 @@
use super::break_join::{join, join_makes_circle};
use super::break_join::join;
use super::explode::explode;
use super::transform::{at_elevation, erase, scale_entities, transform_entities};
use super::{
@@ -20,18 +20,6 @@ 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,
@@ -39,26 +27,18 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// ROTATE Reference: the reference angle (radians), once known. Its first point, and the
/// first of the two new-angle points, are kept in `ref_from`.
/// ROTATE Reference: the reference angle (radians), once known.
ref_angle: Option<f64>,
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
ref_points: bool,
/// SCALE Reference: first point of a reference length given by two points.
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
ref_from: Option<Vec2>,
/// 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 {
@@ -74,12 +54,8 @@ 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> {
@@ -107,120 +83,8 @@ impl SelectThen {
}
}
/// 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.
/// JOIN the selected objects and report what they became.
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
@@ -230,9 +94,6 @@ 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}"))
@@ -265,30 +126,47 @@ impl SelectThen {
}
}
/// SCALE Reference: reference length (typed, or two points), then new length (typed, or a
/// point measured from the base point). The scale factor is new length / reference length.
/// SCALE Reference: reference length (typed, or two points), then new length (typed, a point
/// measured from the base point, or two points after `Points`). The scale factor is new length /
/// reference length.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
if matches!(&i, Input::Keyword(k) if k == "Copy") {
self.copy_mode = true;
s.echo("Scaling a copy of the selected objects.");
return Ok(Step::Continue);
}
let Some(r) = self.ref_len else {
match (self.ref_from, i) {
(None, Input::Point(p)) => self.ref_from = Some(p),
(None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?),
(None, Input::Enter) => self.ref_len = Some(1.0),
(Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
self.ref_from = None;
}
(_, Input::Enter) => return Ok(Step::Done),
_ => {}
}
return Ok(Step::Continue);
};
match (self.ref_points, self.ref_from, i) {
(false, _, Input::Keyword(k)) if k == "Points" => {
self.ref_points = true;
self.ref_from = None;
Ok(Step::Continue)
}
(false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(false, _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(true, None, Input::Point(p)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(None, None, Input::Text(t)) => {
self.ref_len = Some(require_length(number(&t))?);
Ok(Step::Continue)
}
(None, None, Input::Enter) => {
self.ref_len = Some(1.0);
Ok(Step::Continue)
}
(None, Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
Ok(Step::Continue)
}
(Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(Some(r), _, Input::Text(t)) => {
let n = require_length(number(&t))?;
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -296,6 +174,26 @@ impl SelectThen {
}
}
/// The prompt while SCALE Reference collects its lengths.
fn scale_reference_prompt(&self) -> Prompt {
let base = self.pts.first().copied();
match (self.ref_len, self.ref_points, self.ref_from) {
(None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"),
(None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(),
(Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT),
}
}
/// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`.
fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> {
match (self.ref_len, self.ref_points, self.ref_from) {
(Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)),
(Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)),
_ => None,
}
}
/// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a
/// point measured from the base point, or two points after `Points`). The objects turn by the
/// new angle minus the reference angle.
@@ -446,9 +344,6 @@ 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" };
@@ -457,11 +352,7 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
return match (self.ref_len, self.ref_from) {
(Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base),
(None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"),
};
return self.scale_reference_prompt();
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -469,7 +360,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, _) => self.copy_prompt(base),
(Op::Copy, _) => Prompt::new("Specify second point", Accept::POINT).kw(&["Array", "Exit", "Undo"]).base_opt(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, _) => {
@@ -502,14 +393,6 @@ 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);
}
@@ -537,6 +420,10 @@ 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)
@@ -553,7 +440,15 @@ impl Interactive for SelectThen {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(Op::Copy, _, i) => self.copy_input(s, i),
(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::Rotate, 1, inp @ (Input::Point(_) | Input::Text(_) | Input::Enter)) => {
let a = match inp {
Input::Point(p) => self.pts[0].angle_to(p),
@@ -605,16 +500,15 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let m = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) {
Some(f) => Mat3::scale_about(base, f),
None if self.ref_len.is_some() => return Vec::new(),
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -633,7 +527,7 @@ impl Interactive for SelectThen {
k
})
.collect();
out.push(line(base, c));
out.push(line(rubber_from, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
@@ -642,15 +536,18 @@ impl Interactive for SelectThen {
return None;
}
let base = self.pts.first().copied()?;
let matrix = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return None,
};
let mut extra = vec![line(base, c)];
let mut extra = vec![line(rubber_from, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
@@ -679,13 +576,11 @@ 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, ask_mode: false }
DisplaceM { inner: SelectThen::new(op), displacement: false }
}
/// At "Specify base point": objects selected, no point yet.
fn at_base(&self) -> bool {
@@ -698,26 +593,14 @@ 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() {
// 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");
return Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement"]).default("Displacement");
}
self.inner.prompt(s)
}
@@ -734,34 +617,10 @@ 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> {
+4 -55
View File
@@ -3,7 +3,6 @@ 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.
@@ -41,18 +40,6 @@ 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));
@@ -68,56 +55,18 @@ 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) => {
// 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);
// 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;
}
}
EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(mv),
+2 -44
View File
@@ -4,8 +4,7 @@
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, Vec3, ccw_sweep, intersect_ext, line_circle, line_line_infinite,
norm_angle,
Arc, Ellipse, Line, Mat3, PolyVertex, Polyline, Segment, Spline, TAU, Vec2, ccw_sweep, intersect_ext, line_circle, line_line_infinite, norm_angle,
};
use serde_json::{Value, json};
@@ -40,7 +39,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?: 0..99 (polyline, default 10)}",
order? (elevate), precision?}",
)
.interactive(|_| Ok(Box::new(SplineditM::default()))),
CommandSpec::new("lengthen", "Lengthen", run_lengthen)
@@ -123,47 +122,6 @@ 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;
+6 -25
View File
@@ -1,6 +1,6 @@
use super::{
Accept, Chain, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Value, bad, bool_or, curves, json,
other, targets,
number, other, targets,
};
// =====================================================================================
@@ -26,13 +26,7 @@ pub(crate) fn arraypath(
return Err(other("Select objects to array."));
}
let (n, step) = match (count, spacing) {
// 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(sp)) if sp.is_finite() && sp > 0.0 => (((l / sp).floor() as usize).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 })
@@ -67,25 +61,12 @@ 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"))?;
// 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))?;
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))?;
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,
@@ -140,7 +121,7 @@ impl Interactive for PathArrayM {
}
(Some(path), inp @ (Input::Text(_) | Input::Enter)) => {
let n = match &inp {
Input::Text(t) => item_count(t).ok_or_else(|| other("Requires an integer between 1 and 32767."))?,
Input::Text(t) => number(t).filter(|n| *n >= 1.0).ok_or_else(|| other("Requires a count of 1 or more."))? as usize,
_ => 6,
};
arraypath(s, &self.objs, path, Some(n), None, true)?;
+29 -99
View File
@@ -1,7 +1,7 @@
use super::{
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,
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,
};
/// Fit curve: a tangent-continuous pair of arcs (biarc) per segment through every vertex,
@@ -106,21 +106,7 @@ 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).
///
/// 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> {
pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f64) -> 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 {
@@ -128,88 +114,46 @@ 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);
// 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) {
let mut pool: Vec<(Handle, Chain)> = Vec::new();
for o in others {
if *o == h {
continue;
}
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);
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);
if ok && let Some(c) = Chain::of(&oe.kind) {
pool.push((*o, c, (ah, bh)));
pool.push((*o, c));
}
}
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 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 {
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 {
break;
};
let (oh, c, (ah, bh)) = pool.remove(i);
let (oh, c) = pool.remove(i);
let (Some(a), Some(b)) = (c.start(), c.end()) else { continue };
if at(a, ah, en, en_h) {
if a.near(en, tol) {
chain.segs.extend(c.segs);
en_h = bh;
} else if at(b, bh, en, en_h) {
} else if b.near(en, tol) {
chain.segs.extend(c.reversed().segs);
en_h = ah;
} else if at(b, bh, st, st_h) {
} else if b.near(st, tol) {
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)| at(a, st_h, b, en_h)) && chain.segs.len() > 1;
chain.closed = chain.start().zip(chain.end()).is_some_and(|(a, b)| a.near(b, tol)) && chain.segs.len() > 1;
base.vertices = chain.vertices();
base.closed = chain.closed;
let d = s.doc_mut()?;
@@ -220,29 +164,14 @@ 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, 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."))?,
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."))?,
_ => return Err(other("Object selected is not a polyline.")),
};
match opt {
@@ -268,14 +197,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_polyline(s, h, pl, normal)?;
set_kind(s, h, EntityKind::LwPolyline(pl))?;
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), true)?;
let n = pedit_join(s, h, &others, f64_or(p, "fuzz", 0.0))?;
return Ok(json!({ "handle": h.hex(), "joined": n }));
}
"vertex" | "e" => {
@@ -325,7 +254,7 @@ pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> R
}
_ => return Err(bad("pedit", "unknown option")),
}
set_polyline(s, h, pl, normal)?;
set_kind(s, h, EntityKind::LwPolyline(pl))?;
Ok(json!({ "handle": h.hex() }))
}
@@ -539,9 +468,10 @@ impl Interactive for PeditM {
return Ok(Step::Done);
}
let h = self.h.ok_or_else(|| other("No object."))?;
let (pl, normal) = polyline_of(&curves::entity(s, h)?).ok_or_else(|| other("Cannot convert."))?;
let k = curves::entity(s, h)?.kind;
let pl = as_lwpoly(&k).ok_or_else(|| other("Cannot convert."))?;
self.original = Some(pl.vertices.clone());
set_polyline(s, h, pl, normal)?;
set_kind(s, h, EntityKind::LwPolyline(pl))?;
self.phase = PPhase::Main;
Ok(Step::Continue)
}
@@ -614,7 +544,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, true)?;
let n = pedit_join(s, h, &hs, 0.0)?;
s.echo(format!("{n} segments added to polyline"));
s.set_selection(vec![h]);
self.phase = PPhase::Main;
+7 -7
View File
@@ -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::{other, polyline_of, set_kind, set_polyline};
use super::{as_lwpoly, other, set_kind};
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 e = curves::entity(s, h)?;
match e.kind {
let kind = curves::entity(s, h)?.kind;
match kind {
EntityKind::LwPolyline(_) => kept.push(h),
_ if no => {}
_ => {
if let Some((pl, normal)) = polyline_of(&e) {
set_polyline(s, h, pl, normal)?;
k => {
if let Some(pl) = as_lwpoly(&k) {
set_kind(s, h, EntityKind::LwPolyline(pl))?;
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, false)? > 0 {
if pedit_join(s, h, &rest, fuzz)? > 0 {
self.morig.remove(&h);
}
rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some()));
+25 -51
View File
@@ -61,11 +61,8 @@ fn edit(sp: &Spline, opt: &str, p: &Value) -> Result<EntityKind> {
spline(sp.refit(&fit, sp.closed))
}
"polyline" => {
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)))
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)))
}
"move" => {
let (i, to) = (index(p)?, point_req("splinedit", p, "to")?);
@@ -99,9 +96,7 @@ fn spline_close(sp: &Spline) -> Spline {
return sp.clone();
}
let mut out = if sp.fit.len() >= 2 {
// 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)
sp.refit(&sp.fit, true)
} else {
let mut c = sp.control.clone();
c.extend(sp.control.first().copied());
@@ -240,11 +235,11 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
// ---------------- control points ----------------
/// 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.
/// 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.
fn distinct(sp: &Spline) -> usize {
let n = sp.control.len();
if sp.wraps() {
if sp.is_periodic() {
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
@@ -316,7 +311,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.wraps() {
if sp.is_periodic() {
if u <= p + 1 {
return Err(other(format!("A closed spline of degree {p} needs more than {} control points.", p + 1)));
}
@@ -384,30 +379,22 @@ 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. Control points that wrap round are clamped at the seam first.
/// keeps its shape. A periodic spline is clamped at its seam first.
fn add_control(sp: &Spline, at: Vec2) -> Result<Spline> {
let base = if sp.wraps() { sp.clamped().ok_or_else(|| other("Cannot add a control point to this spline."))? } else { sp.clone() };
let base = if sp.is_periodic() { 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_ORDER {
return Err(order_range(sp));
if order < current || order > max {
return Err(other(format!("Requires an order between {current} and {max}.")));
}
if order == current {
return Ok(sp.clone());
@@ -598,22 +585,6 @@ 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 {
@@ -702,15 +673,11 @@ 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) => 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 }))?;
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 }))?;
s.set_selection(Vec::new());
return Ok(Step::Done);
}
@@ -817,7 +784,14 @@ impl Interactive for SplineditM {
None if enter => self.sub = Sub::Vertex,
None => {}
},
Sub::VertexOrder => self.input_order(s, &sp, &i)?,
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::VertexDelete => match point {
Some(p) => {
let u = distinct(&sp);
-212
View File
@@ -639,32 +639,6 @@ 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();
@@ -675,40 +649,6 @@ 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();
@@ -837,155 +777,3 @@ 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, &params).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]);
}
+4 -87
View File
@@ -50,7 +50,6 @@ pub const PROFILE_VARS: &[&str] = &[
"CURSORSIZE",
"PICKFIRST",
"PICKADD",
"COPYMODE",
"PICKDRAG",
"MAXARRAY",
"MEASUREINIT",
@@ -86,31 +85,18 @@ pub fn profile(s: &Session) -> Value {
Value::Object(m)
}
/// The profile variables the drawing keeps in its header rather than in the session's settings.
const DRAWING_VARS: &[&str] = &["SNAPUNIT", "GRIDUNIT"];
/// Set the profile variables named in `values` (an object; other keys are refused). All or
/// nothing: one bad name or value leaves every setting, and the drawing, as they were.
/// nothing: one bad name or value leaves every setting as it was.
pub fn apply(s: &mut Session, values: &Value) -> Result<()> {
let Some(obj) = values.as_object() else { return Err(bad("options", "expected an object of profile variables")) };
let before = s.settings.clone();
// When one of the values is a drawing variable, the drawing as it is: put back whole on a
// refusal, it is the same drawing again, so not marked as changed either.
let touches_drawing = obj.keys().any(|k| DRAWING_VARS.iter().any(|v| v.eq_ignore_ascii_case(k.trim())));
let drawing = if touches_drawing { s.state().ok().map(|st| st.doc.clone()) } else { None };
let put_back = |s: &mut Session| {
s.settings = before.clone();
if let (Some(doc), Ok(st)) = (&drawing, s.state_mut()) {
st.doc = doc.clone();
}
};
for (name, v) in obj {
if !is_profile_var(name) {
put_back(s);
s.settings = before;
return Err(bad("options", format!("{name} is not a profile setting")));
}
if let Err(e) = crate::sysvars::set(s, name, v) {
put_back(s);
s.settings = before;
return Err(bad("options", format!("invalid value for {}: {e}", name.to_ascii_uppercase())));
}
}
@@ -131,8 +117,7 @@ pub fn restore(s: &mut Session, saved: &Value) {
}
}
/// Put every profile variable back to its default, except [`DRAWING_VARS`]: a reset doesn't change
/// the drawing.
/// Put every profile variable back to its default.
pub fn reset(s: &mut Session) {
let d = Settings::default();
let st = &mut s.settings;
@@ -158,24 +143,8 @@ 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;
st.dyndigrip = d.dyndigrip;
st.dyndivis = d.dyndivis;
st.selectioneffect = d.selectioneffect;
st.selectionpreview = d.selectionpreview;
st.previeweffect = d.previeweffect;
st.previewfilter = d.previewfilter;
st.grips = d.grips;
st.gripobjlimit = d.gripobjlimit;
st.selectionarea = d.selectionarea;
st.windowareacolor = d.windowareacolor;
st.crossingareacolor = d.crossingareacolor;
st.selectionareaopacity = d.selectionareaopacity;
st.pickstyle = d.pickstyle;
st.measureinit = d.measureinit;
}
fn run_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -222,56 +191,4 @@ mod tests {
restore(&mut b, &saved);
assert_eq!(profile(&b), saved);
}
#[test]
fn a_refused_change_leaves_the_drawings_snap_and_grid_too() {
let mut s = Session::new();
let before = profile(&s);
let refused = [
json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5], "WINDOWAREACOLOR": 0 }),
json!({ "GRIDUNIT": [4, 5], "LUNITS": 2 }),
json!({ "WINDOWAREACOLOR": 0 }),
];
for bad_one in refused {
assert!(apply(&mut s, &bad_one).is_err(), "{bad_one}");
assert_eq!(profile(&s), before, "{bad_one}");
// The same drawing, so there is nothing new to save.
assert!(!s.state().unwrap().is_dirty(), "{bad_one}");
}
assert!(s.execute("options", &json!({ "reset": true, "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!(profile(&s), before);
// The header entries come back exactly: a zero grid spacing (which reads as the snap
// spacing), and a snap spacing the drawing doesn't have. The refused value comes last, so
// both are written first (the keys are taken in name order).
let header = |s: &Session, n: &str| s.doc().unwrap().header.get(n).cloned();
s.doc_mut().unwrap().header.set("GRIDUNIT", cadcraft_doc::HVal::Point(cadcraft_geom::Vec3::new(0.0, 0.0, 0.0)));
s.doc_mut().unwrap().header.vars.remove("SNAPUNIT");
let (grid, snap) = (header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT"));
assert!(apply(&mut s, &json!({ "GRIDUNIT": [4, 5], "SNAPUNIT": [2, 3], "WINDOWAREACOLOR": 0 })).is_err());
assert_eq!((header(&s, "GRIDUNIT"), header(&s, "SNAPUNIT")), (grid, snap));
}
#[test]
fn reset_puts_every_profile_var_back_except_the_drawings() {
let defaults = profile(&Session::new());
let mut s = Session::new();
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
// A value the variable takes that isn't its default: 0 and 1 swapped, or a number one
// more or less, or an angle.
let was = &defaults[*name];
let n = was.as_f64().unwrap_or(0.0);
let tries = [json!(if n == 0.0 { 1 } else { 0 }), json!(n + 1.0), json!(n - 1.0), json!("15")];
let changed = tries.iter().any(|v| apply(&mut s, &json!({ *name: v })).is_ok() && profile(&s)[*name] != *was);
assert!(changed, "no other value found for {name} (default {was})");
}
assert!(PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)).all(|n| profile(&s)[*n] != defaults[*n]));
apply(&mut s, &json!({ "SNAPUNIT": [2, 3], "GRIDUNIT": [4, 5] })).unwrap();
reset(&mut s);
let after = profile(&s);
for name in PROFILE_VARS.iter().filter(|n| !DRAWING_VARS.contains(n)) {
assert_eq!(after[*name], defaults[*name], "{name}");
}
// The snap and grid spacing are the drawing's, and stay.
assert_eq!((after["SNAPUNIT"].clone(), after["GRIDUNIT"].clone()), (json!([2.0, 3.0]), json!([4.0, 5.0])));
}
}
+5 -5
View File
@@ -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.position_by_name(&name) {
let idx = match d.text_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&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.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
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"))?;
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.position_by_name(&name) {
let idx = match d.dim_styles.iter().position(|t| t.name.eq_ignore_ascii_case(&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.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
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"))?;
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.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
let st = d.linetypes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&from)).ok_or_else(|| bad("rename", "no such linetype"))?;
st.name = to.clone();
// References follow the new name.
let fix = |n: &mut String| {
+1 -1
View File
@@ -59,7 +59,7 @@ fn put(d: &mut Drawing, lt: Linetype, reload: bool, out: &mut Loaded) {
break;
}
}
match d.linetypes.by_name_mut(&lt.name) {
match d.linetypes.iter_mut().find(|l| l.name.eq_ignore_ascii_case(&lt.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,7 +202,6 @@ pub const NO_FILES: &[&str] = &[
"dim",
"mleader",
"leader",
"qleader",
"dimstyle.update",
"dimoverride",
"dimreassociate",
-1
View File
@@ -37,7 +37,6 @@ 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",
-3
View File
@@ -75,8 +75,6 @@ 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,
@@ -182,7 +180,6 @@ impl Default for Settings {
cmdecho: true,
filedia: true,
pickadd: true,
copymode: false,
pickdrag: true,
pickstyle: 1,
gripsize: 5.0,
+3 -3
View File
@@ -161,8 +161,8 @@ impl SpatialIndex {
let infinite = chunks.iter().flat_map(|(off, c)| c.infinite.iter().map(move |i| off + i)).collect();
SpatialIndex {
store: store.clone(),
blocks: (*d.blocks).clone(),
dim_styles: d.dim_styles.to_vec(),
blocks: d.blocks.clone(),
dim_styles: d.dim_styles.clone(),
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))
}
-3
View File
@@ -59,7 +59,6 @@ const SESSION_VARS: &[&str] = &[
"CMDECHO",
"FILEDIA",
"PICKADD",
"COPYMODE",
"PICKDRAG",
"PICKSTYLE",
"GRIPSIZE",
@@ -141,7 +140,6 @@ 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),
@@ -396,7 +394,6 @@ 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),
-2
View File
@@ -67,8 +67,6 @@ 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)),
+91 -56
View File
@@ -532,6 +532,97 @@ fn scale_reference_typed_and_picked() {
assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9));
}
#[test]
fn scale_reference_points_and_copy() {
fn line_ends(s: &Session) -> Vec<Vec2> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(l.b.xy()),
_ => None,
})
.collect()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference 10 via two points, then Points option with two points of length 30 -> (30, 0).
for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify new length");
assert!(p.keywords.contains(&"Points".to_string()));
assert!(p.keywords.contains(&"Copy".to_string()));
s.cmdline("p").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify first point");
s.cmdline("5,5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,35").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9));
// Coinciding Points are rejected without leaving the second-point prompt; a valid point completes.
for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_some());
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,25").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9));
// Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy.
for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 2);
assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9)));
assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9)));
// Copy entered at "Specify new length" combined with Points scales a copy.
for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 3);
assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9)));
}
#[test]
fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
e.common.thickness = 3.0;
if let EntityKind::Text(t) = &mut e.kind {
t.insert.z = 5.0;
}
})
.unwrap();
s.set_selection(vec![h]);
s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
assert!(s.current_prompt().unwrap().message.contains("** SCALE **"));
s.cmdline("2").unwrap();
assert!(s.running.is_none());
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0);
assert_eq!(t.insert.z, 10.0);
}
#[test]
fn layers_and_properties() {
let mut s = Session::new();
@@ -1309,62 +1400,6 @@ 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();
+2 -2
View File
@@ -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.by_name_mut(layout) {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) {
l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name));
}
}
@@ -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.by_name_mut(layout).map(|l| &mut l.ucs_previous),
Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous),
}
}
-31
View File
@@ -229,34 +229,3 @@ 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));
}
-151
View File
@@ -1,151 +0,0 @@
//! 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);
}
@@ -1,98 +0,0 @@
//! Attributes are matched to their block's definitions, and definitions to a reference's
//! attributes, by tag in one lookup each: BURST and ATTSYNC on a reference with many of both.
use std::sync::Arc;
use cadcraft_doc::{Attrib, EntityKind, Handle};
use cadcraft_engine::Session;
use serde_json::json;
/// Block B with definition T and a reference to it carrying T = "v"; with `n` > 0 the block gets
/// `n` more definitions and the reference's attribute is replaced by `n`, the tags `n` long ones
/// alike up to their last characters, no attribute's a definition's.
fn reference(n: usize) -> (Session, Handle) {
let mut s = Session::new();
s.execute("attdef", &json!({"tag": "T", "default": "d", "at": [0, 1], "height": 1.0})).unwrap();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name": "B", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap();
let r = s.execute("insert", &json!({"name": "B", "at": [0, 0], "attribs": {"T": "v"}})).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
if n > 0 {
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
let d = s.doc_mut().unwrap();
let handles: Vec<Handle> = (0..n).map(|_| d.new_handle()).collect();
let blk = Arc::make_mut(d.blocks.get_mut("B").unwrap());
let def = blk.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).unwrap().as_ref().clone();
for (i, h) in handles.into_iter().enumerate() {
let mut e = def.clone();
e.handle = h;
if let EntityKind::AttDef(a) = &mut e.kind {
a.tag = tag('D', i);
}
blk.entities.push(e);
}
d.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let one = ins.attribs[0].clone();
ins.attribs = (0..n).map(|i| Attrib { tag: tag('A', i), ..one.clone() }).collect();
}
})
.unwrap();
}
(s, h)
}
fn attribs(s: &Session, h: Handle) -> Vec<Attrib> {
let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
i.attribs.clone()
}
/// #1923: comparing each attribute with each definition (BURST: for its properties; ATTSYNC: for
/// the value each definition keeps) cost N x N comparisons of whole tags (many seconds here); one
/// lookup each costs milliseconds.
const N: usize = 4000;
#[test]
fn burst_matches_many_attributes_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("burst", &json!({"handles": [h.hex()]})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(), N);
}
#[test]
fn attsync_matches_many_definitions_without_comparing_every_pair() {
let (mut s, h) = reference(N);
let t = std::time::Instant::now();
s.execute("attsync", &json!({"name": "B"})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
// An attribute for each definition (T and the N others), with its default value: the
// reference carried none of their tags.
let a = attribs(&s, h);
assert_eq!(a.len(), N + 1);
assert!(a.iter().all(|a| a.text.value == "d"));
}
#[test]
fn attsync_keeps_the_value_of_the_first_attribute_of_a_tag() {
// A reference carrying two attributes of one tag (in different case, as a file can hold
// them) keeps the first one's value for the definition of that tag.
let (mut s, h) = reference(0);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind {
let mut second = ins.attribs[0].clone();
second.tag = "t".into();
second.text.value = "second".into();
ins.attribs[0].text.value = "first".into();
ins.attribs.push(second);
}
})
.unwrap();
s.execute("attsync", &json!({"name": "B"})).unwrap();
let a = attribs(&s, h);
assert_eq!(a.iter().map(|a| (a.tag.as_str(), a.text.value.as_str())).collect::<Vec<_>>(), [("T", "first")]);
}
-258
View File
@@ -1,258 +0,0 @@
//! 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));
}
-102
View File
@@ -129,105 +129,3 @@ 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
-6
View File
@@ -4,7 +4,6 @@ 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;
@@ -13,7 +12,6 @@ mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
mod attribute_value_baseline;
mod block_description;
@@ -35,7 +33,6 @@ mod compare_export;
mod constraint_geometry;
mod constraint_infer;
mod copy_count;
mod copy_modes;
mod count;
mod dash_block;
mod dash_units;
@@ -87,7 +84,6 @@ 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;
@@ -126,7 +122,6 @@ mod oops_command;
mod options_profile;
mod overkill;
mod parallel_display_list;
mod pedit_heights;
mod pedit_multiple;
mod pedit_splinedit;
mod pick_text;
@@ -148,7 +143,6 @@ mod purge_mlinestyles;
mod purge_prompts;
mod qdim;
mod qdim_modes;
mod qleader;
mod query_entities;
mod quickcalc;
mod recent_commands;
+2 -86
View File
@@ -117,73 +117,6 @@ 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."
@@ -272,31 +205,14 @@ 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}");
}
// 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();
// 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();
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)));
}
-365
View File
@@ -1,365 +0,0 @@
//! 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());
}
+2 -138
View File
@@ -151,19 +151,6 @@ 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();
@@ -294,10 +281,9 @@ 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));
// 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 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.wraps() && before.is_periodic());
assert!(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);
@@ -311,23 +297,6 @@ 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).
@@ -400,108 +369,3 @@ 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);
}
-253
View File
@@ -1,253 +0,0 @@
//! 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}");
}
}
+3 -5
View File
@@ -43,14 +43,12 @@ fn insertion_snaps_to_a_multileader_text() {
#[test]
fn geometric_center_of_a_closed_spline() {
let mut s = Session::new();
// 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).
// A closed fit spline symmetric about (5,5): its centroid is the centre.
s.execute("spline", &json!({"fit": [[0, 5], [5, 0], [10, 5], [5, 10]], "closed": true})).unwrap();
let c = Vec2::new(5.02693946, 5.04916453);
let c = Vec2::new(5.0, 5.0);
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-5, "{:?}", hit.point);
assert!(hit.point.dist(c) < 1e-3, "{:?}", 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();
+1 -47
View File
@@ -21,29 +21,6 @@ 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();
@@ -153,9 +130,7 @@ 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);
// 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));
assert!(sp.eval(0.0).near(Vec2::ZERO, 1e-9) && sp.eval(1.0).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();
@@ -197,27 +172,6 @@ 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,7 +23,6 @@ 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.
@@ -118,60 +117,6 @@ 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();
-8
View File
@@ -64,14 +64,6 @@ 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.
+4 -202
View File
@@ -22,13 +22,11 @@
//! 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::{Bounds2, Vec2};
use cadcraft_geom::Vec2;
use skrifa::instance::{LocationRef, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
use skrifa::raw::FileRef;
@@ -500,8 +498,6 @@ 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()));
}
@@ -839,7 +835,6 @@ 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
@@ -853,7 +848,6 @@ 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.
@@ -873,98 +867,9 @@ 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;
@@ -1014,19 +919,12 @@ 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 {
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
prefs().alt.clone()
}
/// 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.
@@ -1037,7 +935,6 @@ 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).
@@ -1052,22 +949,6 @@ 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())
@@ -1088,8 +969,6 @@ fn fallback_shared(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).
@@ -1109,10 +988,9 @@ 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<GlyphCacheKey, Arc<GlyphOutline>>,
glyphs: HashMap<(usize, usize, u32, GlyphKey), Arc<GlyphOutline>>,
points: usize,
}
@@ -1285,45 +1163,10 @@ 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();
}
@@ -1341,8 +1184,7 @@ fn outline_shared(face: &Face, key: GlyphCacheKey) -> 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 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 g = Arc::new(GlyphOutline { points, 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();
@@ -1759,46 +1601,6 @@ 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::*;
+5 -32
View File
@@ -94,21 +94,6 @@ 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
@@ -361,7 +346,7 @@ impl Spline {
}
/// Reversed direction: control points, weights, fit points and knots (and the fit end
/// tangents swap ends and turn round). A closed spline still starts at its first fit point.
/// tangents swap ends and turn round).
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 {
@@ -369,7 +354,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: if self.closed { reversed_loop(&self.fit) } else { self.fit.iter().rev().copied().collect() },
fit: self.fit.iter().rev().copied().collect(),
closed: self.closed,
fit_opts: crate::FitOptions {
start_tangent: self.fit_opts.end_tangent.map(|t| -t),
@@ -861,25 +846,13 @@ 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)];
// 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 p = Spline::from_fit(&fit, true);
assert!(p.is_periodic());
let c = p.clamped().unwrap();
assert!(!c.wraps() && c.is_periodic(), "the same smooth closed curve");
assert!(!c.is_periodic());
let ((plo, phi), (clo, chi)) = (p.domain(), c.domain());
for i in 0..=20 {
let f = f64::from(i) / 20.0;
+5 -25
View File
@@ -43,10 +43,10 @@ impl Spline {
Spline::fit_with(fit, false, FitOptions::default())
}
/// 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.
/// 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.
pub fn from_fit_points_closed(fit: &[Vec2]) -> Spline {
Spline::fit_with(fit, true, FitOptions::default())
}
@@ -56,31 +56,11 @@ impl Spline {
Spline::fit_with(fit, closed, FitOptions::default())
}
/// 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.
/// Closed with an unclamped (periodic) knot vector, as DXF flags it (group 70 bit 2).
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
+3 -20
View File
@@ -550,39 +550,22 @@ 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),
("sqrt", sqrt),
("uniform", uniform),
("sqrt tangents", sqrt_tangents),
] {
for (name, opts) in [("default", FitOptions::default()), ("tolerance", tolerant), ("tangents", tangents), ("chord", chord)] {
assert_fit_unchanged(&pts, closed, opts, &format!("n={n} closed={closed} {name} zero_every={zero_every}"));
}
}
}
}
// 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.
// Large point sets: open interpolation (banded) and a closed one (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);
+39 -640
View File
@@ -67,13 +67,10 @@ impl KnotParam {
pub struct FitOptions {
#[serde(default)]
pub knots: KnotParam,
/// 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.
/// Unit tangent direction at the first fit point; `None` lets the end follow the points.
#[serde(default)]
pub start_tangent: Option<Vec2>,
/// Tangent at the last fit point, as the start one.
/// Unit tangent direction at the last fit point.
#[serde(default)]
pub end_tangent: Option<Vec2>,
/// Largest allowed distance between the curve and a fit point; 0 passes through them.
@@ -82,22 +79,14 @@ pub struct FitOptions {
}
impl FitOptions {
/// Normalised tangents (non-finite directions and those too short to normalise dropped) and a
/// finite, non-negative tolerance: what [`Spline::fit_with`] stores.
/// Normalised tangents (zero or non-finite directions dropped) and a finite, non-negative
/// tolerance: what a spline stores.
pub fn sanitized(self) -> FitOptions {
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);
let dir = |t: Option<Vec2>| t.filter(|v| v.x.is_finite() && v.y.is_finite() && v.len() > 1e-12).map(Vec2::normalized);
FitOptions {
knots: self.knots,
start_tangent: valid(self.start_tangent),
end_tangent: valid(self.end_tangent),
start_tangent: dir(self.start_tangent),
end_tangent: dir(self.end_tangent),
tolerance: if self.tolerance.is_finite() { self.tolerance.max(0.0) } else { 0.0 },
}
}
@@ -114,34 +103,31 @@ 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 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
/// are periodic and ignore end tangents; 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 = 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())
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
}
/// 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_end_derivatives(fit, closed, self.fit_opts)
Spline::fit_with(fit, closed, self.fit_opts)
}
/// Which knot parametrisation produced this spline's knots from its fit points (DXF files
@@ -204,26 +190,12 @@ impl Spline {
.unwrap_or(KnotParam::Chord)
}
/// 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.
/// Apply an affine map to the control and fit points and turn the end tangents with it.
pub fn transform(&mut self, m: &Mat3) {
for c in self.control.iter_mut().chain(self.fit.iter_mut()) {
*c = m.apply(*c);
}
// 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)
})
};
let turn = |t: Option<Vec2>| t.map(|v| m.apply_vec(v).normalized()).filter(|v| v.len() > 0.5);
self.fit_opts.start_tangent = turn(self.fit_opts.start_tangent);
self.fit_opts.end_tangent = turn(self.fit_opts.end_tangent);
}
@@ -252,32 +224,10 @@ 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();
// 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) {
if n < 2 || (n == 2 && !tangents) {
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 {
@@ -287,8 +237,7 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
return s;
}
let u = params(fit, opts.knots, false);
// 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.
// Tangents are directions; the derivative's length is the curve length in parameter space.
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);
@@ -306,131 +255,7 @@ fn open_fit(fit: &[Vec2], opts: FitOptions) -> Spline {
if n > MAX_INTERP_POINTS {
return 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)
interpolate(fit, &u, d0, d1).unwrap_or_else(through_control)
}
/// Global interpolation: one control point per fit point plus one per end-derivative
@@ -676,13 +501,9 @@ 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);
}
@@ -718,7 +539,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: stored, closed, ..Spline::default() };
let s = Spline { degree: p, knots, control, fit: fit.to_vec(), closed, ..Spline::default() };
s.is_valid().then_some(s)
}
@@ -835,7 +656,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, tangent: Option<Vec2>) -> Spline {
fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64) -> 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();
@@ -862,13 +683,6 @@ fn closed_fit(fit: &[Vec2], kind: KnotParam, tol: f64, tangent: Option<Vec2>) ->
{
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.
@@ -903,9 +717,7 @@ mod tests {
fn passes_through(s: &Spline, fit: &[Vec2], tol: f64) -> bool {
let u = params(fit, s.fit_opts.knots, s.closed);
// 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)
fit.iter().zip(&u).all(|(f, t)| s.eval(*t).dist(*f) < tol)
}
#[test]
@@ -934,8 +746,6 @@ 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);
}
}
@@ -954,11 +764,9 @@ 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: 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).
// One tangent only, 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() + 2 && passes_through(&one, &fit, 1e-3));
assert!(one.is_valid() && one.control.len() == fit.len() + 1 && passes_through(&one, &fit, 1e-3));
let two = [Vec2::ZERO, Vec2::new(4.0, 0.0)];
let b = Spline::fit_with(
&two,
@@ -966,309 +774,9 @@ 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);
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());
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);
}
#[test]
@@ -1325,10 +833,9 @@ 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, as AutoCAD 2024 builds the closed spline (the curve
// without a tolerance, which keeps the one asked for).
// Too tight a tolerance interpolates.
let tiny = Spline::fit_with(&fit, true, FitOptions { tolerance: 1e-9, ..FitOptions::default() });
assert_eq!((&tiny.knots, &tiny.control, tiny.fit_opts.tolerance), (&exact.knots, &exact.control, 1e-9));
assert_eq!(tiny.control.len(), exact.control.len());
// Every parametrisation approximates.
for k in KnotParam::ALL {
let s = Spline::fit_with(&fit, true, FitOptions { tolerance: tol, knots: k, ..FitOptions::default() });
@@ -1371,20 +878,6 @@ 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());
@@ -1422,19 +915,6 @@ 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
@@ -1471,87 +951,6 @@ 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)]
+1 -57
View File
@@ -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(s.domain().1).near(fit[4], 1e-9));
assert!(s.eval(1.0).near(fit[4], 1e-9));
}
#[test]
@@ -201,62 +201,6 @@ 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);
+12 -4
View File
@@ -617,12 +617,20 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
p(&mut t, 10, b.scale);
f(&mut t, 43, b.rotation);
i(&mut t, 176, 1);
// Attribute values by their ATTDEF in the block, the definitions gathered by tag once.
let defs = d.block(&b.block).map(|blk| blk.attdefs_by_tag()).unwrap_or_default();
// Attribute values by their ATTDEF in the block.
let defs: Vec<(Handle, &str)> = d
.block(&b.block)
.map(|blk| {
blk.entities
.iter()
.filter_map(|e| if let EntityKind::AttDef(ad) = &e.kind { Some((e.handle, ad.tag.as_str())) } else { None })
.collect()
})
.unwrap_or_default();
let mut n = 0i64;
for a in &b.attribs {
let Some(def) = defs.get(&cadcraft_doc::TagKey(&a.tag)) else { continue };
s(&mut t, 330, &def.handle.hex());
let Some((h, _)) = defs.iter().find(|(_, tag)| tag.eq_ignore_ascii_case(&a.tag)) else { continue };
s(&mut t, 330, &h.hex());
i(&mut t, 177, n);
f(&mut t, 44, 0.0);
s(&mut t, 302, &a.text.value);
-10
View File
@@ -74,8 +74,6 @@ struct Rx {
block: Option<String>,
/// The points HATCH boundary curves may still be sampled into.
curves: hatch::CurvePoints,
/// LTYPE records read with only their first `MAX_LINETYPE_ELEMENTS` dash elements.
linetypes_cut: usize,
/// IMAGE entity handle, as read (a repeated one reassigned) → its IMAGEDEF handle (upper case).
image_defs: HashMap<Handle, String>,
}
@@ -294,14 +292,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
}
crate::dxf_raw::read(&secs, &mut d);
crate::dxf_clip::read(&mut d);
if rx.linetypes_cut > 0 {
let (n, max) = (rx.linetypes_cut, craft_dxf::lin_pat::MAX_LINETYPE_ELEMENTS);
d.read_notes.push(if n == 1 {
format!("DXF: 1 linetype has more than {max} dash elements; only its first {max} were read.")
} else {
format!("DXF: {n} linetypes have more than {max} dash elements; only the first {max} of each were read.")
});
}
if rx.curves.cut > 0 {
// Echoed on open, returned by OPEN and listed by the CLI, so a coarse boundary is never silent.
let n = rx.curves.cut;
+4 -19
View File
@@ -251,23 +251,10 @@ 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" {
@@ -278,8 +265,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).map_or(first_layout, String::as_str);
if let Some(l) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
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) {
for (_, _, e) in ents {
l.entities.push(e);
}
@@ -337,12 +324,11 @@ 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) = layout_at.get(&lname).and_then(|&i| d.layouts.get_mut(i)) {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
l.entities.push(e);
}
}
@@ -431,7 +417,6 @@ 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;
@@ -447,7 +432,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) = layout_at.get(lname).and_then(|&i| d.layouts.get_mut(i)) {
if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) {
l.entities.sort_by_key(key);
}
} else if let Some(b) = d.blocks.get_mut(name.as_str()) {

Some files were not shown because too many files have changed in this diff Show More