Compare commits

..
31 Commits
Author SHA1 Message Date
Tanish Manku cda891fb4e UNDO stops at a REFCLOSE Save that wrote an xref's file, instead of bringing back an edit it can't save 2026-11-23 13:30:21 -07:00
Tanish Manku 39fca9e2a7 Xref baseline: keep the file's modification time as the system gives it, so a time before 1970 counts 2026-11-23 13:30:21 -07:00
Tanish Manku 506ad531eb REFEDIT: refuse a reference with several columns or rows instead of opening its first instance 2026-11-23 13:30:21 -07:00
Tanish Manku 003ab113c2 REFCLOSE Save: refuse a host block the xref's drawing defines differently under its name 2026-11-23 13:20:39 -07:00
Tanish Manku 273437af7a REFCLOSE Save: a host linetype brings the text styles its dashes are drawn in 2026-11-23 13:17:36 -07:00
Tanish Manku d0d027ac8f REFCLOSE Save: a dangling reference the xref's file already had is written as it was 2026-11-23 13:15:38 -07:00
Tanish Manku 4c004d5dd5 REFCLOSE Save: count only the xref's dimensions that are written as losing their associations 2026-11-23 13:13:09 -07:00
Tanish Manku 3e98ef30e7 REFEDIT: an xref's version and form come from the read that gave its drawing and stamp 2026-11-23 13:10:19 -07:00
Tanish Manku 4840d576a5 REFEDIT: an outer reference REFEDIT can't open offers no nested level 2026-11-23 13:08:04 -07:00
Tanish Manku 07bdd66b1d REFEDIT docs: an xref's backup is kept only when ISAVEBAK is on 2026-11-23 12:55:51 -07:00
Tanish Manku 9e7663b25c REFEDIT.LEVELS is classified for the automation roots: it touches no file
The PR's new command was on no list, which main's every_command_is_classified
test refuses. Its "path" is a path of nested references, not a file.
2026-11-20 19:25:05 -07:00
Tanish Manku 10727f5025 REFEDIT: a nested reference is offered only when it opens with its parents
Discovery checked each reference's own transform, while opening it checks the
transform with everything above it: two small uniform scales together could be
offered and then refused.
2026-11-20 18:55:52 -07:00
Tanish Manku 1515833f2c REFCLOSE Save: an xref's backup follows ISAVEBAK, as SAVE's does
With ISAVEBAK off, SAVE keeps no .bak; the write-back of an xref kept one anyway.
2026-11-20 18:53:05 -07:00
Tanish Manku 28d8ba72c5 REFCLOSE Save: name the dimension associations an xref's write-back leaves out
Loading an xref drops its dimensions' associations, so writing it back leaves
them out of the file. When the part written back had associative dimensions,
the save says so and lists "dimension associations" in notSaved, pointing at
the backup that keeps them. A dimension drawn during the edit attaches to the
host's copies, whose handles mean nothing in the xref's file: it is written
without those associations, and counted too.
2026-11-20 18:51:28 -07:00
Tanish Manku 5af8fc020a REFCLOSE Save: an xref is not written naming a block it doesn't define
A host dimension style copied into the xref's drawing brings the blocks its
arrowheads are drawn with. A block the written objects still name that the
drawing lacks, such as another xref of the host added with REFSET, refuses the
save: the file, its backup and the edit stay as they were.
2026-11-20 18:47:03 -07:00
Tanish Manku a3e04070be REFCLOSE Save: test that an xref's write-back reports what SAVE would
The merge replaced the PR's own loss report with main's lost_writing and
lost_message (the conflict was in cmd/file.rs). This covers a case the PR's copy
missed: a proxy an R2000 DXF xref can't keep is named, with the reason and the
backup that still has it.
2026-11-20 18:44:39 -07:00
Tanish Manku 210a99ecc8 REFEDIT xref tests: the tests that read and write DWG allow the in-process converter themselves
main now refuses to convert a DWG in process unless the caller allows it, so these
two tests failed after the merge.
2026-11-20 18:43:25 -07:00
Tanish Manku bc703cb134 REFEDIT and REFCLOSE: an xref is read and written only inside the automation roots
refedit and refclose touch files, so they move to the FILES list. REFEDIT checks
that the xref's file may be read and written before an edit begins; REFCLOSE Save
checks the file it writes and its .bak before anything is read or written, so
roots put in force since the edit began hold too. A refused save leaves the xref,
its backup and the host as they were, and the edit stays open.
2026-11-20 18:42:31 -07:00
Tanish Manku 84eb20b5c0 Merge #2355: blocks: REFEDIT edits xrefs in place and writes their drawing back; nested references, faded drawing and Edit Reference bar
# Conflicts:
#	crates/engine/src/cmd/file.rs
#	crates/render/src/draw.rs
#	crates/render/src/lib.rs
#	crates/render/src/pipeline.rs
#	crates/render/src/viewports.rs
2026-11-20 18:32:01 -07:00
Francesco BV 27e408d91b REFEDIT/REFCLOSE on xrefs: per-drawing baseline, safer save checks
From the second automated review of #2355:

- The "loaded" stamp was one per file for the whole process, taken from
  the path after the bytes were read. Each xref block now keeps its own
  baseline (Block::xref_stamp, session state), taken from the opened
  file before and after the read (None when it changed meanwhile), and
  another drawing loading the file no longer moves it. REFEDIT uses the
  stamp of the one read its handles and version come from, and refuses
  unless that is the drawing's baseline; an unknown stamp counts as
  changed. The process-wide LOADED cache is gone.
- REFCLOSE Save checks the stamp before reading, of the read itself,
  and once more just before the file is replaced (narrowing, not
  closing, the window for another program's save).
- It refuses while the xref's file is open in another drawing tab (it
  was checked only when the edit began).
- It refuses a file the xref could no longer load (more than
  MAX_XREF_OBJECTS, counted as import counts: load::object_count).
- bring_symbols counts distinct symbols only, and refuses the save past
  the budget instead of writing with symbols missing; it copies host
  multileader styles (with their text style) and table styles (with
  their cell styles' text styles) too.
- refedit.levels no longer offers a nested reference REFEDIT would
  refuse (scaled differently in X and Y, flat), nor what is below it.
- Faded copies keep the object's own transparency; the renderer fades
  them by the current XFADECTL, so changing it during the edit shows.
2026-11-20 10:11:24 +01:00
Francesco BV 195c052931 REFEDIT xref tests: folders cleaned up on every exit; a host-only layer
Each test's folder is now an owned guard removed on drop, so a skipped
symlink test or a failed assertion no longer leaves its files behind.

The save test drew its new line after a `layer` call that does nothing
in JSON (`.ok()` hid it), so the line stayed on layer 0 and the check
that host layers come along could not fail. It makes "Added" current
first (layer.new) and asserts the line and the file's layer table.

Review of #2355 (CodeRabbit, tests/it/refedit_xref.rs:30 and :117).
2026-11-20 09:56:07 +01:00
Francesco BV 7d1d0ba55b render: the REFEDIT fade looks the working set up once per display list
entity_parts asked RefEdit::is_working, a scan of the working set, for
every object drawn, and read XFADECTL from the header each time: 50,000
working objects meant about a billion handle comparisons per rebuild.
The working set is now a hash set built with XFADECTL once per display
list (render::Fade) and shared by the serial, parallel and viewport
builders.

Review of #2355 (CodeRabbit, render/src/draw.rs:50).
2026-11-20 09:55:38 +01:00
Francesco BV 8920c0fb6f i18n: Chinese label for Reference Nesting Levels
main now requires every command label in zh.tsv (#1129); refedit.levels
came in with this branch.
2026-11-20 09:14:55 +01:00
Francesco BV 68fbe896a7 render: XFADECTL fade in its own function
After the merge with main, entity_parts went past clippy's cognitive
complexity limit (32/30) with the REFEDIT fade in it.
2026-11-20 08:36:48 +01:00
Francesco BV f9756d5083 rustfmt the REFCLOSE write-back and its tests 2026-11-20 08:32:24 +01:00
Francesco BV 7a199cc2e1 REFCLOSE: say what the xref's file couldn't keep
SAVE and SAVEAS list what the writer drops; the write-back wrote the
source drawing straight through and said nothing, so a DWG xref holding
types the DWG writer can't keep (or a 2013+ DXF one holding solids with
SAT-text geometry) lost them silently.

REFCLOSE now counts them as SAVE does, for the version the file is
written in (file::loss_writing: not_saved_as for DWG, sat_text_dropped
for 2013+ DXF), echoes the same warning prefixed with the file and
naming the backup that still has them, and lists them in the result's
notSaved. Nothing lost, no warning.

Review of #2355, point 3.
2026-11-20 08:29:25 +01:00
Francesco BV 88ef222cdf REFEDIT xref tests: follow main's io and Insert after the merge
cadcraft_io::read and write take a path now, and Insert has a clip.
2026-11-20 08:29:18 +01:00
Francesco BV 64e0b5c2a4 REFCLOSE: write an xref back in the version it was read in
The write-back used IoHooks::write, which picks the version from the
drawing: an R2000 DWG xref came back as a 2004 DWG (a DWG is written at
2004 or later by default) and an R12 DXF one as R2000. An xref is often
someone else's file, and a version change can lock its author out.

REFEDIT now records the file's version (a DWG's from its first bytes, a
DXF's $ACADVER) and whether it is a binary DXF, and REFCLOSE writes it
back through the write_as hook at that version and form. A version
CADCraft doesn't write (R12) is refused before the edit begins, so no
work is lost; so is a build without the write_as hook. REFEDIT's result
names the version.

Review of #2355, point 2.
2026-11-20 08:22:23 +01:00
Francesco BV b27cc3ce22 REFCLOSE: write an xref back the way SAVE writes a drawing
The write-back made its own temporary file (`<file>.cadcraft-tmp`, opened
with a plain truncating write) and copied the backup with fs::copy, so a
symbolic link planted at either path took the write: the drawing went
into the link's target and the xref's path became that link (CWE-59).

It now goes through what SAVE uses: the backup is file::backup (written
atomically, a link at the .bak replaced, never written through) and the
new file atomic_write::write_atomic_with (an exclusively created
temporary file renamed over the file). The file written is the one the
xref's path led to when the edit began; REFCLOSE refuses when the path
leads elsewhere by then (a link put there during the edit).

The backup is named by file::backup_path, as SAVE names it: site.dwg's
is site.bak, site.dxf's site.dxf.bak, so two xrefs of one name in one
folder no longer share (and overwrite) one site.bak.

Review of #2355, points 1 and 4.
2026-11-20 08:20:51 +01:00
Francesco BV b355f1e14a Merge origin/main into pr/xref-edit-in-place
Conflicts: the doc re-export (Raster next to XrefSource), the system
variable table (XCLIPFRAME next to XFADECTL), the canvas paint calls
(painter is a reference now), the Italian and Ukrainian labels (both
sides kept), and docs/gaps.md and docs/target-app-parity.md, taken from
main: pull requests don't edit those docs any more (AGENTS.md), so the
rows this change affects are named in the PR instead.
2026-11-20 08:16:53 +01:00
Francesco BVandClaude Opus 5.5 ad6314967f blocks: REFEDIT edits xrefs in place and writes their drawing back
REFEDIT on an xref (or a block that came with one) edits it in place, and
REFCLOSE Save writes the change into the source drawing (the old file
kept as .bak, symbol prefixes removed, host symbols copied, handles kept)
and reloads the xref. Refused for read-only files, files locked by
another program or open in another tab, and files changed since they
were loaded or during the edit. Nested references are picked through
their parents (path, nested, refedit.levels, "Select nesting level
[OK/Next]"). Everything outside the working set is drawn faded
(XFADECTL), and an Edit Reference bar offers Add to/Remove from Working
Set and Save/Discard Changes. Gap F2.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 19:58:37 +01:00
49 changed files with 2492 additions and 2112 deletions
+1 -2
View File
@@ -38,7 +38,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
nightly: ${{ github.event_name == 'schedule' }}
dry-run: ${{ github.event_name == 'schedule' }}
app-name: cadcraft
app-title: CADCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -60,4 +60,3 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1 -1
View File
@@ -39,7 +39,7 @@ pub use header::{HVal, Header};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
pub use refedit::{RefEdit, WorkItem};
pub use refedit::{RefEdit, WorkItem, XrefSource};
pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
+30
View File
@@ -42,6 +42,36 @@ pub struct RefEdit {
/// Block objects taken out of the working set with their edits (block coordinates, the block
/// object's handle).
pub released: Vec<Entity>,
/// The nested references picked through to reach the edited block: block references inside
/// block definitions, outermost first. Empty when the picked reference's own block is edited.
pub path: Vec<Handle>,
/// Set when the edited block comes from an external reference: REFCLOSE Save writes it back
/// into its source drawing.
pub xref: Option<XrefSource>,
}
/// Where an xref edited in place is written back to.
#[derive(Clone, Debug, PartialEq)]
pub struct XrefSource {
/// The xref (its block name in this drawing).
pub xref: String,
/// The source drawing file.
pub file: String,
/// `file` with every symbolic link resolved when the edit began: the file that is written.
/// The save is refused when `file` leads somewhere else by then.
pub real: String,
/// The version the file was in when the edit began, as its `$ACADVER` code ("AC1015"): it
/// is written back in that version (`None`: in the drawing's own).
pub version: Option<String>,
/// Whether the file is a binary DXF (written back as one).
pub binary: bool,
/// The block of the source drawing being edited; `None` for its model space.
pub block: Option<String>,
/// The file's size and modification time when the edit began.
pub stamp: Option<(u64, std::time::SystemTime)>,
/// Edited block objects (their handles in this drawing) and the objects of the source
/// drawing they were loaded from.
pub sources: Vec<(Handle, Handle)>,
}
impl RefEdit {
+6
View File
@@ -728,6 +728,11 @@ pub struct Block {
/// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>,
/// An xref's file as its loaded objects were read from it: size and modification time (as the
/// system gives it, so a time before 1970 is kept too). Kept per drawing, so an edit in place (REFEDIT) can tell whether
/// the file changed since this drawing loaded it (session state; not saved).
#[serde(skip)]
pub xref_stamp: Option<(u64, std::time::SystemTime)>,
}
/// The load state of an external reference.
@@ -774,6 +779,7 @@ impl Block {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
}
}
}
File diff suppressed because it is too large Load Diff
+69 -11
View File
@@ -134,7 +134,7 @@ struct Ctx {
}
/// The folder of the host drawing at `host` (a file path).
fn folder(host: Option<&Path>) -> Option<PathBuf> {
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> {
let p = host?.parent()?;
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
}
@@ -293,8 +293,17 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
Ok(out.is_file().then_some(out))
}
/// The first bytes of a file [`read`] keeps with the drawing (enough for a DWG's version and the
/// binary DXF sentinel).
const HEAD_BYTES: usize = 4096;
/// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them
/// even when the path is pointed at another file meanwhile; `None` when the file changed while it
/// was read (or the system can't tell its time), so an edit in place refuses until it is reloaded.
/// And the first [`HEAD_BYTES`] of those bytes, so what is told from them (a DWG's version, a
/// binary DXF) describes the same read.
fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
#[cfg(not(target_arch = "wasm32"))]
{
@@ -303,7 +312,9 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
let limit = MAX_XREF_BYTES.min(left);
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
let len = f.metadata().map_err(|e| e.to_string())?.len();
let meta = f.metadata().map_err(|e| e.to_string())?;
let len = meta.len();
let before = stamp_of(&meta);
let too_big = || {
if limit < MAX_XREF_BYTES {
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
@@ -321,7 +332,10 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
return Err(too_big());
}
cx.bytes = cx.bytes.saturating_add(n);
(hooks.read)(&bytes, &file.to_string_lossy())
let after = f.metadata().ok().as_ref().and_then(stamp_of);
let read_as = before.filter(|b| Some(*b) == after);
let head = bytes.get(..HEAD_BYTES).unwrap_or(&bytes).to_vec();
Ok(((hooks.read)(&bytes, &file.to_string_lossy())?, read_as, head))
}
#[cfg(target_arch = "wasm32")]
{
@@ -330,6 +344,33 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
}
}
/// A file's size and modification time: how an edit in place (REFEDIT) tells whether an xref's
/// file changed since it was read ([`cadcraft_doc::Block::xref_stamp`]). The time is kept as the
/// system gives it: counted from 1970, a file dated before then would have none and always look
/// changed.
pub(crate) type Stamp = (u64, std::time::SystemTime);
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn stamp_of(m: &std::fs::Metadata) -> Option<Stamp> {
Some((m.len(), m.modified().ok()?))
}
/// The [`Stamp`] of the file at `file` now.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn stamp(file: &Path) -> Option<Stamp> {
stamp_of(&std::fs::metadata(file).ok()?)
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn stamp(_file: &Path) -> Option<Stamp> {
None
}
/// Read the drawing file `file` (with the size limits of xref loading), with the [`Stamp`] and the
/// first bytes of the bytes read (see [`read`]).
pub(crate) fn read_file(file: &Path) -> Result<(Drawing, Option<Stamp>, Vec<u8>), String> {
read(file, &mut Ctx::new(None))
}
/// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
/// own path.
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
@@ -393,8 +434,14 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
clear(d, &key);
let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
Ok((x, file)) => match import(d, &key, &x, cx) {
Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
Ok((x, file, read_as)) => match import(d, &key, &x, cx) {
Ok(()) => {
// This drawing's own baseline: another drawing loading the file later doesn't move it.
if let Some(b) = d.blocks.get_mut(&key) {
Arc::make_mut(b).xref_stamp = read_as;
}
(XrefStatus::Loaded, file.to_string_lossy().into_owned())
}
Err(e) => {
// Whatever made it in before the failure goes again. A fetch that failed imported
// nothing, so it doesn't pay for a second scan of the block table.
@@ -409,7 +456,13 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: &
}
/// Read the drawing referenced as `path` and load its own attached xrefs into it.
fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
fn fetch(
path: &str,
host: Option<&Path>,
chosen: bool,
cx: &mut Ctx,
depth: usize,
) -> Result<(Drawing, PathBuf, Option<Stamp>), (XrefStatus, String)> {
let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
if depth >= MAX_BLOCK_DEPTH {
return Err(unresolved("xrefs are nested too deeply"));
@@ -423,7 +476,7 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
return Err(unresolved("too many referenced files"));
}
cx.files += 1;
let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
cx.chain.push(canon);
let nested: Vec<String> =
x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
@@ -434,15 +487,20 @@ fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usi
}
}
cx.chain.pop();
Ok((x, file))
Ok((x, file, read_as))
}
/// The objects loading drawing `x` as an xref counts against [`MAX_XREF_OBJECTS`]: its model
/// space and every block's.
pub(crate) fn object_count(x: &Drawing) -> usize {
x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()))
}
/// Bring referenced drawing `x` into xref `key`: its model space becomes the block's objects, its
/// symbols and blocks are added as `key|name` (dependent symbols the host already has keep the
/// host's settings, so layer changes survive a reload).
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
cx.objects = cx.objects.saturating_add(count);
cx.objects = cx.objects.saturating_add(object_count(x));
if cx.objects > MAX_XREF_OBJECTS {
return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
}
-22
View File
@@ -343,11 +343,6 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
ttt_where(objs, |_| true)
}
/// [`ttt`] among the circles `ok` accepts.
pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Option<Circle> {
let [(o1, p1), (o2, p2), (o3, p3)] = objs;
let mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0;
@@ -355,20 +350,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
starts.push([cen.x, cen.y, rad.max(1e-3)]);
if let Some(c) = Circle::from_3_points(p1, p2, p3) {
starts.push([c.center.x, c.center.y, c.radius]);
} else {
// The picks lie in one line. When the circles picked are centred on it too, every Newton
// step from a start on that line stays on it: start off it as well, on both sides, from
// the circle through the two picks farthest apart and a point beside them.
let (a, b) = [(p1, p2), (p1, p3), (p2, p3)].into_iter().max_by(|x, y| x.0.dist(x.1).total_cmp(&y.0.dist(y.1))).unwrap_or((p1, p3));
let span = a.dist(b);
let n = (b - a).normalized().perp();
if span.is_finite() && span > 0.0 && n.is_finite() {
for side in [1.0, -1.0] {
if let Some(c) = Circle::from_3_points(a, b, (a + b) / 2.0 + n * (span * side)) {
starts.push([c.center.x, c.center.y, c.radius]);
}
}
}
}
let mut best: Option<(f64, Circle)> = None;
let scale = rad.max(p1.dist(p2)).max(1e-6);
@@ -398,9 +379,6 @@ pub fn ttt_where(objs: [(TanObj, Vec2); 3], ok: impl Fn(&Circle) -> bool) -> Opt
continue;
}
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c));
+5 -74
View File
@@ -2,7 +2,6 @@ use super::{
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
point_param, size_param,
};
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
let c = if let Some(center) = point_param(p, "center") {
@@ -52,8 +51,6 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) struct CircleM {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
pts: Vec<Vec2>,
/// 3P: the circle or arc each point was picked on with a tangent snap, by point.
tans: Vec<Option<snap::SnapCurve>>,
diameter: bool,
/// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>,
@@ -72,22 +69,18 @@ impl Interactive for CircleM {
match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(0, _) if self.diameter => {
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance()
}
(0, _) => {
let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
.kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
let p =
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
}
(1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT,
)
.base_opt(self.pts.last().copied())
.deferred(),
.base_opt(self.pts.last().copied()),
(2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT,
@@ -127,14 +120,7 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
Some(Circle::new(*c, r))
}
1 if self.pts.len() == 3 => match self.three_points() {
Some(c) => Some(c),
None => {
self.pts.pop();
self.tans.truncate(self.pts.len());
return Err(crate::EngineError::Other("Circle does not exist.".into()));
}
},
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]),
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
_ => None,
};
@@ -144,29 +130,6 @@ impl Interactive for CircleM {
}
Ok(Step::Continue)
}
// 3P: a point picked with a tangent snap makes the circle tangent to that curve (#1512).
Input::Deferred(d) if self.mode == 1 => {
let tan = (d.mode == snap::mode::TAN && !matches!(d.curve, snap::SnapCurve::Line { .. })).then_some(d.curve);
self.tans.resize(self.pts.len(), None);
self.tans.push(tan);
self.input(s, Input::Point(d.at))
}
// A tangent picked for the radius: the circle around the center that touches the
// curve, on the side it was picked (#1512).
Input::Deferred(d) if self.mode == 0 && self.pts.len() == 1 => {
let Some(&c) = self.pts.first() else { return Ok(Step::Continue) };
// Around the picked curve's own center the circle would lie on it, not touch it.
let concentric =
matches!(d.curve, snap::SnapCurve::Circle { center, .. } | snap::SnapCurve::Arc { center, .. } if center.near(c, 1e-9));
let touch = d.curve.perpendiculars(c, d.at).into_iter().filter(|_| !concentric).min_by(|a, b| a.dist(d.at).total_cmp(&b.dist(d.at)));
match touch.map(|t| c.dist(t)).filter(|r| *r > 1e-12 && r.is_finite()) {
Some(r) => {
finish_circle(s, Circle::new(c, r))?;
Ok(Step::Done)
}
None => Err(crate::EngineError::Other("No circle around the center is tangent there.".into())),
}
}
Input::Text(t) if self.mode == 0 && self.pts.len() == 1 => {
let v = number(&t).ok_or_else(|| crate::EngineError::Other("Requires numeric distance or second point.".into()))?;
let r = if self.diameter { v / 2.0 } else { v };
@@ -211,38 +174,6 @@ impl Interactive for CircleM {
}
}
impl CircleM {
/// The 3P circle: through the three points, or tangent to the curves picked with TAN.
fn three_points(&self) -> Option<Circle> {
let [a, b, c] = <[Vec2; 3]>::try_from(self.pts.as_slice()).ok()?;
if self.tans.iter().all(Option::is_none) {
return Circle::from_3_points(a, b, c);
}
let tan = |i: usize| self.tans.get(i).copied().flatten();
// A plain point is a circle of radius zero to pass through; an arc is solved as its circle.
let target = |i: usize, p: Vec2| {
let circle = match tan(i) {
Some(snap::SnapCurve::Circle { center, radius } | snap::SnapCurve::Arc { center, radius, .. }) => Circle::new(center, radius),
_ => Circle::new(p, 0.0),
};
crate::cmd::curves::TanObj::Circle(circle)
};
let pts = [a, b, c];
// The circle must touch an arc within its sweep, not elsewhere on the arc's circle, and
// not be the picked circle itself (which lies on it rather than touching it).
let touches = |found: &Circle| {
pts.iter().enumerate().all(|(i, p)| {
tan(i).is_none_or(|t| {
let same = matches!(target(i, *p), crate::cmd::curves::TanObj::Circle(o)
if o.center.dist(found.center) + (o.radius - found.radius).abs() <= 1e-9 * o.radius);
!same && t.contains(target(i, *p).touch(found))
})
})
};
crate::cmd::curves::ttt_where([(target(0, a), a), (target(1, b), b), (target(2, c), c)], touches)
}
}
fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+7 -5
View File
@@ -721,12 +721,13 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
/// ([`crate::atomic_write::write_atomic_with`]). Nothing
/// to keep when there is no file yet. A file that doesn't look like a drawing
/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone.
/// Returns whether the backup was written. Also used for an xref REFEDIT writes back.
#[cfg(not(target_arch = "wasm32"))]
fn backup(path: &std::path::Path) -> std::io::Result<()> {
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
let mut src = match std::fs::File::open(path) {
Ok(f) if f.metadata()?.is_file() => f,
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Ok(_) => return Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(e),
};
let (head, tail, len) = ends(&mut src)?;
@@ -735,7 +736,7 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
// the roots (or to another computer) isn't looked at.
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) {
log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
return Ok(());
return Ok(false);
}
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private
// 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
@@ -761,7 +762,8 @@ fn backup(path: &std::path::Path) -> std::io::Result<()> {
}
std::io::Write::write_all(out, &head)?;
std::io::copy(&mut src, out).map(|_| ())
})
})?;
Ok(true)
}
/// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
-58
View File
@@ -466,61 +466,3 @@ fn plot_path_extension_picks_the_format_like_export() {
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn osnap_in_mspace_skips_vplayer_frozen_layers() {
let mut s = Session::new();
s.execute("layer.new", &json!({"name": "Hidden"})).unwrap();
s.execute("line", &json!({"points": [[60, -25], [70, -25]]})).unwrap();
let line_h = s.doc().unwrap().model.iter().last().unwrap().handle;
s.execute("properties.set", &json!({"handles": [line_h], "layer": "Hidden"})).unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.execute("mview", &json!({"p1": [20, 20], "p2": [220, 120]})).unwrap();
let vp_h = viewports(&s, "Layout1").last().unwrap().0;
s.execute("vplayer", &json!({"handles": [vp_h], "freeze": ["Hidden"]})).unwrap();
s.execute("mspace", &json!({"handle": vp_h})).unwrap();
let ap = s.pixel_size() * s.settings.aperture.max(1.0);
let d = ap * 0.5;
let model_before = s.doc().unwrap().model.len();
for (ovr, pt, name) in [
("end", format!("{},-25", 60.0 + d), "Endpoint"),
("mid", format!("{},-25", 65.0 + d), "Midpoint"),
("nea", format!("63,{}", -25.0 + d), "Nearest"),
] {
s.cmdline("line").unwrap();
s.cmdline(ovr).unwrap();
s.cmdline(&pt).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some(format!("No {name} found for specified point.").as_str()),
"{ovr} should not snap to a line on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
}
assert_eq!(s.doc().unwrap().model.len(), model_before, "no new line should be created");
// Running osnaps through snap_cursor must also ignore the VPLAYER-frozen layer.
s.settings.osmode = crate::snap::mode::END | crate::snap::mode::MID | crate::snap::mode::NEA;
let cs = s.snap_cursor(
cadcraft_geom::Vec2::new(60.0 + d, -25.0),
&crate::snap::tracking::CursorQuery { base: None, deferred: false, corner: false, aperture: ap, tol: ap, now: 0.0, shift: false },
);
assert!(cs.snap.is_none(), "running osnap should not snap to a VPLAYER-frozen line: {:?}", cs.snap);
// A block reference on layer "0" containing an entity on "Hidden" must also not snap.
s.execute("block", &json!({"name": "B", "base": [60, -25], "handles": [line_h]})).unwrap();
let model_with_block = s.doc().unwrap().model.len();
s.cmdline("line").unwrap();
s.cmdline("end").unwrap();
s.cmdline(&format!("{},-25", 60.0 + d)).unwrap();
assert_eq!(
s.log.last().map(String::as_str),
Some("No Endpoint found for specified point."),
"end should not snap to a block entity on a VPLAYER-frozen layer; log: {:?}",
s.log
);
s.cmdline("").unwrap();
assert_eq!(s.doc().unwrap().model.len(), model_with_block);
}
+6 -5
View File
@@ -48,6 +48,8 @@ pub const FILES: &[&str] = &[
"publish",
"qsave",
"recover",
"refclose",
"refedit",
"reinit",
"saveas",
"script",
@@ -260,9 +262,8 @@ pub const NO_FILES: &[&str] = &[
"attdisp.normal",
"attdisp.on",
"attdisp.off",
"refedit",
"refedit.levels",
"refset",
"refclose",
"bedit",
"bsave",
"bsaveas",
@@ -514,9 +515,9 @@ mod tests {
use std::collections::BTreeSet;
/// Words in a command's parameter doc that usually name a file. In these commands they don't:
/// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
/// direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
/// `array` and `arraypath` follow a path of objects, `refedit.levels` reports paths of nested
/// references, and `blocks.reference.grips` reports a direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"];
/// The words of a command's documentation, lower case.
fn words(doc: &str) -> BTreeSet<String> {
+11 -27
View File
@@ -127,31 +127,18 @@ pub fn snap_name(m: u32) -> &'static str {
}
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
snap_candidates_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`snap_candidates`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn snap_candidates_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
// A base that is not a number would give meaningless perpendiculars and tangents.
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 || base.is_some_and(|b| !b.is_finite()) {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
return Vec::new();
}
let mut out: Vec<SnapHit> = crate::snap::osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen).into_iter().collect();
for h in crate::snap::osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, frozen) {
if !out.iter().any(|o| o.same(&h, aperture)) {
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
let extra = osmode & mode::HATCH;
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
for h in per_mode {
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
out.push(h);
}
}
@@ -365,15 +352,12 @@ impl Session {
Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture.
let prompt = self.current_prompt();
let (doc, space, frozen) = {
let st = self.state()?;
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
};
let space = self.space();
let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base);
let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred);
match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point,
+2 -3
View File
@@ -75,9 +75,8 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>,
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this
/// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
/// prompt (a point with no base yet, e.g. the first point of a line). Elsewhere a deferred
/// pick arrives as the plain point it was picked at.
pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell): ortho does not bend the opposite corner, so the rectangle keeps its area.
+3
View File
@@ -108,6 +108,9 @@ impl Session {
return Ok(Some(label));
}
let st = self.state_mut()?;
if let Some(why) = st.undo.last().and_then(|snap| cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)) {
return Err(EngineError::Other(why));
}
let Some(snap) = st.undo.pop() else { return Ok(None) };
let cur = st.swap_in(snap);
let label = cur.label.clone();
+123 -550
View File
@@ -65,24 +65,6 @@ pub struct SnapHit {
}
impl SnapHit {
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// The same snap as `o`, for a Tab list without repeats: the same mode at the same point
/// (within a millionth of `aperture`), deferred or not alike (and if deferred, on the same
/// curve), and from the same source (this space, or one viewport). Overlapping viewports can
/// show different model points at one paper point; each stays a candidate, since DIST
/// measures in the model units of the viewport picked.
pub(crate) fn same(&self, o: &SnapHit, aperture: f64) -> bool {
self.mode == o.mode
// Deferred snaps on different curves at one provisional point stay apart: the line
// drawn from each depends on its curve.
&& self.deferred.map(|d| d.curve) == o.deferred.map(|d| d.curve)
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, aperture * 1e-6)
}
/// The command input a pick at this snap gives: a deferred snap or a plain point.
pub fn input(&self) -> crate::Input {
match self.deferred {
@@ -128,16 +110,12 @@ impl SnapCurve {
}
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve
/// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
match self {
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
let u = (p - *center).normalized();
if u == Vec2::ZERO {
// On an arc, the point within its sweep.
vec![match *self {
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(picked),
_ => Circle::new(*center, *radius).closest(picked),
}]
vec![Circle::new(*center, *radius).closest(picked)]
} else {
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
}
@@ -224,34 +202,15 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no
/// base and `deferred` set (the prompt says it can resolve them, `Prompt.deferred`),
/// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
/// known. With a base and `deferred` set, tangents to circles and circular arcs are deferred too
/// (CIRCLE's radius: the circle around the base that touches the curve, #1512); an elliptical arc
/// or a spline keeps its ordinary tangent from the base. Deferred hits only win
/// where no other snap does (they are as unspecific as Nearest).
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest).
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> {
osnap_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`osnap`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn osnap_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Option<SnapHit> {
if osmode == 0 || osmode & mode::OFF != 0 {
return None;
}
let ix = crate::spatial::index(d, space);
osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with(
d: &Drawing,
@@ -263,7 +222,7 @@ pub(crate) fn osnap_with(
base: Option<Vec2>,
deferred: bool,
) -> Option<SnapHit> {
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred, &[]).0
osnap_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred).0
}
/// Find the best object snap and retain the local-space primitives gathered for that query.
@@ -277,18 +236,17 @@ pub(crate) fn osnap_with_neighborhood(
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> (Option<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (None, None);
}
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hit, prims)) => (hit, Some(prims)),
None => (None, None),
};
let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() {
return (best.map(|(h, _)| h), near_prims);
return (best, near_prims);
}
let model = Space::Model;
let model_ix = crate::spatial::index(d, &model);
@@ -299,47 +257,42 @@ pub(crate) fn osnap_with_neighborhood(
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
continue;
}
let Some((cands, prims)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
continue;
};
let clip = Some(view.model_clip);
// The rank was found in model units: paper units are model units times the scale.
let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
let first = finish(cands.clone(), &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip);
// The model clip is the box round the viewport as the model sees it, larger than the
// viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
// best of the others that is on it, as Tab ranks them.
let hit = first.and_then(|f| {
project(f)
.or_else(|| finish_all(cands, &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project))
});
if let Some((hit, rank)) = hit
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
let hit = osnap_in(
d,
&model,
&model_ix,
model_cursor,
model_aperture,
osmode,
model_base,
deferred,
&view.viewport.frozen_layers,
Some(view.model_clip),
)
.and_then(|h| view.hit(h));
if let Some(hit) = hit
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
{
best = Some((hit, rank));
best = Some(hit);
}
}
(best.map(|(h, _)| h), near_prims)
(best, near_prims)
}
/// How a hit ranks against the hits of another space (paper space, another viewport) and, for
/// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
/// a perpendicular or tangent on the object under the cursor or a center found from its curve,
/// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
#[derive(Clone, Copy, Debug)]
struct Rank {
tier: u8,
score: f64,
}
impl Rank {
fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
}
fn beats(&self, other: &Rank) -> bool {
self.cmp(other).is_lt()
}
#[allow(clippy::too_many_arguments)]
fn osnap_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
}
#[allow(clippy::too_many_arguments)]
@@ -354,92 +307,7 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Option<(SnapHit, Rank)>, Vec<Prim>)> {
let (cands, near_prims) = collect_in(d, space, ix, cursor, aperture, osmode, frozen)?;
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
}
/// Every snap of `osmode` under the aperture round `cursor`, best first: Tab cycles through
/// these. Each mode's points of every object nearby, the intersections, perpendicular and
/// tangent points from `base`, the centers found from their curves, the deferred snaps and the
/// nearest point of each object, ranked as [`osnap`] ranks them, without repeats and at most
/// [`MAX_CYCLE`]; in viewports too, as [`osnap`] snaps.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
osnap_all_with_frozen(d, space, cursor, aperture, osmode, base, deferred, &[])
}
/// [`osnap_all`] skipping entities (and block leaves) on `frozen` layers in `space`.
#[allow(clippy::too_many_arguments)]
pub fn osnap_all_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
frozen: &[String],
) -> Vec<SnapHit> {
if osmode == 0
|| osmode & mode::OFF != 0
|| !cursor.is_finite()
|| !(aperture.is_finite() && aperture > 0.0)
|| base.is_some_and(|b| !b.is_finite())
{
return Vec::new();
}
let ix = crate::spatial::index(d, space);
let mut out: Vec<(SnapHit, Rank)> = Vec::new();
if let Some((cands, prims)) = collect_in(d, space, &ix, cursor, aperture, osmode, frozen) {
out = finish_all(cands, &prims, cursor, aperture, osmode, base, deferred, None);
}
let model = Space::Model;
let views = viewport::near(d, space, cursor, aperture);
if !views.is_empty() {
let model_ix = crate::spatial::index(d, &model);
for view in views {
let (mc, ma, mb) = (view.to_model(cursor), aperture / view.scale, base.map(|p| view.to_model(p)));
if !mc.is_finite() || !(ma.is_finite() && ma > 0.0) || mb.is_some_and(|p| !p.is_finite()) {
continue;
}
let Some((cands, prims)) = collect_in(d, &model, &model_ix, mc, ma, osmode, &view.viewport.frozen_layers) else { continue };
// The rank was found in model units: paper units are model units times the scale.
out.extend(
finish_all(cands, &prims, mc, ma, osmode, mb, deferred, Some(view.model_clip))
.into_iter()
.filter_map(|(h, r)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }))),
);
}
}
out.sort_by(|a, b| a.1.cmp(&b.1));
let mut unique: Vec<SnapHit> = Vec::with_capacity(out.len().min(MAX_CYCLE));
for (h, _) in out {
if unique.len() >= MAX_CYCLE {
break;
}
if !unique.iter().any(|u| u.same(&h, aperture)) {
unique.push(h);
}
}
unique
}
/// Most snaps [`osnap_all`] offers.
const MAX_CYCLE: usize = 256;
/// The candidate snap points near `cursor` (each with its mode) and the primitives near it:
/// [`gather_in`]'s, plus the intersections between those primitives.
#[allow(clippy::too_many_arguments)]
fn collect_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
frozen: &[String],
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -477,7 +345,8 @@ fn collect_in(
}
}
}
Some((cands, near_prims))
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -521,7 +390,18 @@ pub(crate) fn extendable(p: &Prim) -> bool {
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
/// when the drawing can't be searched.
pub(crate) fn gather_in(
pub(crate) fn gather(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[])
}
fn gather_in(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
@@ -578,19 +458,7 @@ pub(crate) fn gather_in(
Some((cands, near_prims))
}
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
/// its [`Rank`].
///
/// In order of preference (the rank's tier):
/// 0. the snap point within `aperture` of the cursor that scores best (see [`snap_score`]),
/// perpendicular and tangent points from the base point included;
/// 1. with a base point, a perpendicular or tangent on an object that passes within `aperture`,
/// wherever its point lies (see [`from_base_on_objects`]), or the center of a circle, arc or
/// ellipse under the cursor (see [`curve_centers`]): the object nearest the cursor;
/// 2. a deferred perpendicular or tangent (no base point yet);
/// 3. Nearest.
///
/// [`finish_all`] keeps every candidate in this order, for Tab.
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
#[allow(clippy::too_many_arguments)]
fn finish(
mut cands: Vec<(u32, Vec2)>,
@@ -601,254 +469,87 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Option<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
) -> Option<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
if osmode & mode::PER != 0 {
match p {
Prim::Seg(Segment::Line(l)) => cands.push((mode::PER, l.project(bp))),
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
// not offered, and the far side is still found.
Prim::Seg(Segment::Arc { arc, .. }) => {
let curve = SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end };
cands.extend(curve.perpendiculars(bp, bp).into_iter().map(|q| (mode::PER, q)));
}
Prim::Circle(c) => cands.push((mode::PER, c.closest(bp))),
Prim::Infinite { base: b0, dir, .. } => cands.push((mode::PER, *b0 + *dir * (bp - *b0).dot(*dir))),
Prim::Ellipse(e) => cands.extend(curves::ellipse_perpendiculars(e, bp).into_iter().map(|q| (mode::PER, q))),
Prim::Spline(s) => cands.extend(curves::spline_perpendiculars(s, bp).into_iter().map(|q| (mode::PER, q))),
_ => {}
}
}
if osmode & mode::TAN != 0 {
let pts = match p {
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
cands.extend(pts.into_iter().map(|t| (mode::TAN, t)));
}
}
}
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
// Prefer more specific modes when nearly equidistant.
let best = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (snap_score(*m, *p, cursor, aperture), *m, *p))
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, m, p)) = best {
return Some((SnapHit::plain(m, p), Rank { tier: 0, score }));
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
// Prefer more specific modes when nearly equidistant.
let da = snap_score(a.0, a.1, cursor, aperture);
let db = snap_score(b.0, b.1, cursor, aperture);
da.total_cmp(&db)
});
if let Some((m, p)) = best {
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
}
// A perpendicular or tangent on the object under the cursor, or the center found from its
// curve, only when no snap point is in the aperture: the Midpoint or Quadrant under the cursor
// wins over the center of the same curve, as in AutoCAD. Of the two, the object nearer the
// cursor; on a tie (the same curve), the perpendicular or tangent.
let on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible)
.into_iter()
.min_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)))
.map(|(h, r, _)| (h, r));
let center = curve_centers(near_prims, cursor, aperture, osmode)
.into_iter()
.filter(|(_, c)| visible(*c))
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score }));
match (on_object, center) {
(Some(o), Some(c)) => return Some(if c.1.beats(&o.1) { c } else { o }),
(Some(h), None) | (None, Some(h)) => return Some(h),
(None, None) => {}
}
// With a base, perpendiculars are resolved from it above; only tangents are left to defer.
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
if deferred && let Some(h) = deferred_hit(near_prims, cursor, aperture, deferrable, clip) {
let score = h.point.dist(cursor);
return Some((h, Rank { tier: 2, score }));
if base.is_none()
&& deferred
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
{
return Some(h);
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
let nb = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible)).min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((score, p)) = nb {
return Some((SnapHit::plain(mode::NEA, p), Rank { tier: 3, score }));
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
};
for p in near_prims {
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
}
if let Some((_, p)) = nb {
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
}
}
None
}
/// [`finish`], keeping every candidate with its [`Rank`], in the order [`finish`] prefers them:
/// the snap points best first, then the perpendiculars and tangents on the objects under the
/// cursor and the centers found from their curves, then the deferred snaps, then the nearest point
/// of each object nearby.
#[allow(clippy::too_many_arguments)]
fn finish_all(
mut cands: Vec<(u32, Vec2)>,
near_prims: &[Prim],
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Vec<(SnapHit, Rank)> {
let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let mut out: Vec<(SnapHit, Rank)> = cands
.iter()
.filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture)
.map(|(m, p)| (SnapHit::plain(*m, *p), Rank { tier: 0, score: snap_score(*m, *p, cursor, aperture) }))
.collect();
// Of several points on one object (a circle's two tangents), the one nearer the cursor first,
// as `finish` picks it; the sort below is stable.
let mut on_object = from_base_on_objects(&from_base, near_prims, cursor, aperture, visible);
on_object.sort_by(|a, b| a.1.score.total_cmp(&b.1.score).then(a.2.total_cmp(&b.2)));
out.extend(on_object.into_iter().map(|(h, r, _)| (h, r)));
out.extend(
curve_centers(near_prims, cursor, aperture, osmode)
.into_iter()
.filter(|(_, c)| visible(*c))
.map(|(score, c)| (SnapHit::plain(mode::CEN, c), Rank { tier: 1, score })),
);
let deferrable = if base.is_some() { osmode & mode::TAN } else { osmode };
if deferred {
let hits = deferred_hits(near_prims, cursor, aperture, deferrable, clip);
out.extend(hits.into_iter().map(|h| (h, Rank { tier: 2, score: h.point.dist(cursor) })));
}
if osmode & mode::NEA != 0 {
let near = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible));
out.extend(near.map(|(score, p)| (SnapHit::plain(mode::NEA, p), Rank { tier: 3, score })));
}
out.sort_by(|a, b| a.1.cmp(&b.1));
out
}
/// The point of `p` closest to `cursor` among its visible points within `aperture`, with its
/// distance: each segment's closest point is checked before the closest is chosen, so a curve
/// whose closest point is clipped away (outside a viewport) still offers the visible one.
fn nearest_point(p: &Prim, cursor: Vec2, aperture: f64, visible: &impl Fn(Vec2) -> bool) -> Option<(f64, Vec2)> {
let mut nb: Option<(f64, Vec2)> = None;
let mut consider = |c: Vec2| {
let dd = c.dist(cursor);
if visible(c) && dd <= aperture && nb.is_none_or(|(bd, _)| dd < bd) {
nb = Some((dd, c));
}
};
for s in prim_segments(p) {
consider(fix_circle(&s).closest(cursor));
}
if let Prim::Circle(c) = p {
consider(c.closest(cursor));
}
nb
}
/// The perpendicular and tangent points from the base point `base` (none without one), each
/// with the index in `near_prims` of the object it lies on. At a `deferred` prompt the tangents to
/// circles and arcs are left out: the prompt resolves them itself (CIRCLE's radius, #1512).
fn base_snaps(near_prims: &[Prim], osmode: u32, base: Option<Vec2>, cursor: Vec2, deferred: bool) -> Vec<FromBase> {
let mut from_base: Vec<FromBase> = Vec::new();
let Some(bp) = base else { return from_base };
for (prim, p) in near_prims.iter().enumerate() {
let mut found = |mode: u32, points: Vec<Vec2>| from_base.extend(points.into_iter().map(|point| FromBase { mode, point, prim }));
if osmode & mode::PER != 0 {
let pts = match p {
Prim::Seg(Segment::Line(l)) => vec![l.project(bp)],
// Both antipodes, filtered to the arc's sweep: a perpendicular in the gap is
// not offered, and the far side is still found. From the centre, the point of
// the arc under the cursor.
Prim::Seg(Segment::Arc { arc, .. }) => {
SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end }.perpendiculars(bp, cursor)
}
// Both antipodes too, so a pick on the far side of the circle snaps there
// rather than across it. From the centre every point is perpendicular: the
// one under the cursor.
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }.perpendiculars(bp, cursor),
Prim::Infinite { base: b0, dir, .. } => vec![*b0 + *dir * (bp - *b0).dot(*dir)],
Prim::Ellipse(e) => curves::ellipse_perpendiculars(e, bp),
Prim::Spline(s) => curves::spline_perpendiculars(s, bp),
_ => Vec::new(),
};
found(mode::PER, pts);
}
if osmode & mode::TAN != 0 {
let pts = match p {
// A deferred prompt resolves tangents to circles and arcs itself.
Prim::Seg(Segment::Arc { .. }) | Prim::Circle(_) if deferred => Vec::new(),
// Only the tangent points that lie on the arc itself (not its circle).
Prim::Seg(Segment::Arc { arc, .. }) => Circle::new(arc.center, arc.radius)
.tangent_points(bp)
.into_iter()
.filter(|t| arc.contains_angle(arc.center.angle_to(*t)))
.collect(),
Prim::Circle(c) => c.tangent_points(bp),
Prim::Ellipse(e) => curves::ellipse_tangents(e, bp),
Prim::Spline(s) => curves::spline_tangents(s, bp),
_ => Vec::new(),
};
found(mode::TAN, pts);
}
}
from_base
}
/// Center, as in AutoCAD: with the cursor over a circle, an arc (also a polyline's) or an
/// ellipse, the running Center snap finds its center however far away it is. Each center comes
/// with how far the curve is from `cursor` (its score); [`finish`] tries them only when no snap
/// point is in the aperture. Empty unless Center is among `osmode`.
fn curve_centers(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32) -> Vec<(f64, Vec2)> {
let mut out = Vec::new();
if osmode & mode::CEN == 0 {
return out;
}
// The work limit counts the curves only, so straight segments before them can't hide them.
let curves = prims.iter().filter_map(|p| match p {
Prim::Circle(c) => Some((c.center, c.closest(cursor))),
Prim::Seg(s @ Segment::Arc { arc, .. }) => Some((arc.center, fix_circle(s).closest(cursor))),
Prim::Ellipse(e) => Some((e.center, e.closest(cursor))),
_ => None,
});
for (center, on) in curves.take(2000) {
let d = on.dist(cursor);
if center.is_finite() && d.is_finite() && d <= aperture {
out.push((d, center));
}
}
out
}
/// Prefer more specific modes when nearly equidistant.
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
}
/// A perpendicular ([`mode::PER`]) or tangent ([`mode::TAN`]) point found from the base point,
/// with the index in `near_prims` of the object it lies on.
struct FromBase {
mode: u32,
point: Vec2,
prim: usize,
}
/// The perpendiculars and tangents from the base point on the objects that pass within
/// `aperture` of the cursor, wherever the foot or tangent point lies (#2800), each with its
/// [`Rank`] (tier 1, scored by the cursor's distance to the object) and its distance to the cursor.
///
/// These snaps name an object, not a spot on it: you can't know in advance where the foot of a
/// perpendicular will be, so, as in AutoCAD, hovering anywhere over the object finds it and the
/// point jumps there. [`finish`] asks for this only when no snap point lies within the aperture,
/// so an endpoint, midpoint or intersection under the cursor still wins.
///
/// [`finish`] takes the object nearest the cursor; of several points on it (an arc's two
/// antipodes, a circle's two tangents), the one nearest the cursor.
fn from_base_on_objects(
found: &[FromBase],
near_prims: &[Prim],
cursor: Vec2,
aperture: f64,
visible: impl Fn(Vec2) -> bool,
) -> Vec<(SnapHit, Rank, f64)> {
let mut out = Vec::new();
if found.is_empty() {
return out;
}
// `near_prims` holds every object whose box comes near the cursor, so the true distance is
// checked here. It is measured once per object, and only for objects with a point to offer:
// an ellipse or a spline is measured on its tessellation.
let mut reach: Vec<Option<f64>> = vec![None; near_prims.len()];
for f in found.iter().filter(|f| visible(f.point)) {
let Some(slot) = reach.get_mut(f.prim) else { continue };
let to_object = *slot.get_or_insert_with(|| near_prims.get(f.prim).map_or(f64::INFINITY, |p| distance_to_prim(p, cursor)));
// A NaN distance (from a degenerate object) never qualifies.
if to_object.is_nan() || to_object > aperture {
continue;
}
out.push((SnapHit::plain(f.mode, f.point), Rank { tier: 1, score: to_object }, f.point.dist(cursor)));
}
out
}
/// The distance from `cursor` to the nearest point of `p`, measured as Nearest measures it.
fn distance_to_prim(p: &Prim, cursor: Vec2) -> f64 {
// A ray runs one way from its start (an xline both ways, as its segment does).
if let Prim::Infinite { base, dir, ray: true } = p {
return (*base + *dir * (cursor - *base).dot(*dir).max(0.0)).dist(cursor);
}
prim_segments(p).iter().map(|s| fix_circle(s).closest(cursor).dist(cursor)).fold(f64::INFINITY, f64::min)
}
/// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000;
@@ -1147,47 +848,6 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
/// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
/// perpendicular on the same circle, and to the deferred snap of each curve nearby. A click takes
/// the nearest one ([`deferred_hit`]).
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
if osmode & (mode::TAN | mode::PER) == 0 {
return hits;
}
for p in prims {
let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
Prim::Seg(Segment::Arc { arc, .. }) => SnapCurve::Arc { center: arc.center, radius: arc.radius, start: arc.start, end: arc.end },
Prim::Seg(Segment::Line(l)) => SnapCurve::Line { a: l.a, b: l.b },
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
_ => continue,
};
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
// anywhere.
let at = match curve {
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
SnapCurve::Line { a, b } => {
let l = cadcraft_geom::Line::new(a, b);
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
}
};
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
continue;
}
let modes: &[(u32, &'static str)] = match curve {
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
};
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
}
}
hits
}
/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`.
fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Option<SnapHit> {
let mut best: Option<(f64, SnapHit)> = None;
@@ -1461,24 +1121,6 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
/// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
/// On a circle with no base point, its quadrant, then the deferred tangent and the deferred
/// perpendicular at the same spot.
#[test]
fn osnap_all_ranks_every_candidate() {
let d = drawing();
let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
// Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
assert_eq!(all.first().map(|h| h.point), osnap(&d, &Space::Model, cursor, 0.5, modes, None, false).map(|h| h.point));
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, mode::QUA | mode::TAN | mode::PER, None, true).is_empty());
}
#[test]
fn center_quadrant_tangent() {
let d = drawing();
@@ -1495,70 +1137,6 @@ mod tests {
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9));
}
/// #2800: hovering anywhere over the line finds the perpendicular, though its foot (2,0) is
/// six units from the cursor; it used to snap only within the aperture of the foot.
#[test]
fn perpendicular_from_base_anywhere_on_the_line() {
let d = drawing();
let h = osnap(&d, &Space::Model, Vec2::new(8.0, 0.1), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
assert!(h.point.near(Vec2::new(2.0, 0.0), 1e-9), "{h:?}");
assert_eq!(h.mode, mode::PER);
}
/// #2800: the tangent point is found from anywhere on the circle; of its two tangent points
/// from the base, the one nearer the cursor.
#[test]
fn tangent_from_base_anywhere_on_the_circle() {
let d = drawing();
// From (30,0), 10 from the centre (20,0) of the radius-2 circle: the tangent points are
// at cos = 2/10 from the line to the base, (20.4, ±1.9596).
let upper = Vec2::new(20.4, 2.0 * (1.0f64 - 0.04).sqrt());
let on_circle = Vec2::new(20.0 - 2.0 * std::f64::consts::FRAC_1_SQRT_2, 2.0 * std::f64::consts::FRAC_1_SQRT_2);
let h = osnap(&d, &Space::Model, on_circle, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
assert!(h.point.near(upper, 1e-9), "{h:?}");
let mirrored = Vec2::new(on_circle.x, -on_circle.y);
let h = osnap(&d, &Space::Model, mirrored, 0.5, mode::TAN, Some(Vec2::new(30.0, 0.0)), false).unwrap();
assert!(h.point.near(Vec2::new(upper.x, -upper.y), 1e-9), "{h:?}");
}
/// A circle offers both perpendicular points from the base, so a pick on its far side snaps
/// there, not to the near side across the circle (CodeRabbit on #2825).
#[test]
fn perpendicular_from_base_on_a_circle_takes_the_side_under_the_cursor() {
let d = drawing();
// The circle at (20,0), radius 2, seen from (30,0): perpendicular at (22,0) and (18,0).
let base = Some(Vec2::new(30.0, 0.0));
let far = osnap(&d, &Space::Model, Vec2::new(18.1, 0.1), 0.5, mode::PER, base, false).unwrap();
assert!(far.point.near(Vec2::new(18.0, 0.0), 1e-9), "{far:?}");
// Away from both points, at (19, √3) on the circle: 2 from (18,0) and √12 from (22,0).
let top = osnap(&d, &Space::Model, Vec2::new(19.0, 3.0f64.sqrt()), 0.5, mode::PER, base, false).unwrap();
assert!(top.point.near(Vec2::new(18.0, 0.0), 1e-9), "{top:?}");
let near = osnap(&d, &Space::Model, Vec2::new(21.9, 0.1), 0.5, mode::PER, base, false).unwrap();
assert!(near.point.near(Vec2::new(22.0, 0.0), 1e-9), "{near:?}");
}
/// With several objects under the aperture, the one nearest the cursor gives the
/// perpendicular, even when another object's foot is nearer.
#[test]
fn perpendicular_from_base_takes_the_object_nearest_the_cursor() {
let d = drawing();
// 0.4 above the horizontal line and 0.2 right of the vertical one: the vertical line wins,
// with its foot (5,4) farther from the cursor than the horizontal line's (2,0).
let h = osnap(&d, &Space::Model, Vec2::new(5.2, 0.4), 0.5, mode::PER, Some(Vec2::new(2.0, 4.0)), false).unwrap();
assert!(h.point.near(Vec2::new(5.0, 4.0), 1e-9), "{h:?}");
}
/// A snap point under the cursor still beats a perpendicular whose foot is away from it, and
/// an object outside the aperture gives none, though its box is near.
#[test]
fn perpendicular_from_base_yields_to_points_under_the_cursor() {
let d = drawing();
let base = Some(Vec2::new(2.0, 4.0));
let h = osnap(&d, &Space::Model, Vec2::new(9.9, 0.05), 0.5, mode::END | mode::PER, base, false).unwrap();
assert_eq!((h.point, h.mode), (Vec2::new(10.0, 0.0), mode::END));
assert!(osnap(&d, &Space::Model, Vec2::new(8.0, 0.7), 0.5, mode::PER, base, false).is_none());
}
#[test]
fn ortho_and_polar() {
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
@@ -1601,14 +1179,9 @@ mod tests {
let df = h.deferred.unwrap();
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
assert_eq!(h.input(), crate::Input::Deferred(df));
// With a base it is an ordinary tangent, unless the prompt resolves it (CIRCLE's radius).
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), false).unwrap();
// With a base it is an ordinary tangent.
let t = osnap(&d, &Space::Model, Vec2::new(19.9, 1.9), 1.0, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
assert!(t.deferred.is_none() && t.name == "Tangent");
let t = osnap(&d, &Space::Model, at, 0.5, mode::TAN, Some(Vec2::new(10.0, 0.0)), true).unwrap();
assert_eq!(t.name, "Deferred Tangent");
// A perpendicular from the base is still resolved from it.
let p = osnap(&d, &Space::Model, Vec2::new(2.0, 0.2), 0.5, mode::PER, Some(Vec2::new(2.0, 5.0)), true).unwrap();
assert!(p.deferred.is_none() && p.point.near(Vec2::new(2.0, 0.0), 1e-9));
// A specific snap still wins over a deferred one.
let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
assert_eq!(q.mode, mode::QUA);
+8 -47
View File
@@ -482,38 +482,13 @@ impl Tracker {
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Track> {
self.track_with_frozen(d, space, cursor, aperture, tol, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn track_with_frozen(
&mut self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base, frozen);
let t = self.find(d, space, cursor, aperture, tol, cfg, base);
self.last = t.clone();
t
}
#[allow(clippy::too_many_arguments)]
fn find(
&self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> {
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
return None;
}
@@ -563,7 +538,7 @@ impl Tracker {
// 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) {
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) {
@@ -613,26 +588,12 @@ pub fn candidate(
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
) -> Option<Acquired> {
candidate_with_frozen(d, space, cursor, hit, aperture, cfg, base, &[])
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn candidate_with_frozen(
d: &Drawing,
space: &Space,
cursor: Vec2,
hit: Option<&SnapHit>,
aperture: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Acquired> {
if !can_acquire(cursor, aperture, cfg) {
return None;
}
let ix = crate::spatial::index(d, space);
let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen).map(|(_, p)| p).unwrap_or_default();
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
}
@@ -828,7 +789,7 @@ impl crate::Session {
s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase;
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
let (doc, space) = (st.doc.clone(), st.edit_space());
if !raw.is_finite() {
return CursorSnap { point: raw, ..Default::default() };
}
@@ -837,10 +798,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
let ix = crate::spatial::index(&doc, &space);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred);
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) {
(0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
_ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base),
};
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
if let Some(h) = hit {
@@ -855,7 +816,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
}
if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) {
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0.
let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode
+1
View File
@@ -311,6 +311,7 @@ mod tests {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
};
blk.entities
.push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 })));
+2
View File
@@ -81,6 +81,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
// How much objects outside the working set fade while a reference is edited in place (REFEDIT).
("XFADECTL", Kind::Int(0, 90), Def::Int(50)),
];
/// The standard lineweights in hundredths of a millimetre.
+1 -3
View File
@@ -115,7 +115,6 @@ mod offset_ellipse_side;
mod offset_move;
mod oops_command;
mod options_profile;
mod osnap_opened_drawings;
mod overkill;
mod parallel_display_list;
mod pedit_multiple;
@@ -144,6 +143,7 @@ mod recent_commands;
mod rectang_ortho;
mod rectang_polygon_order;
mod refedit;
mod refedit_xref;
mod region;
mod rename_cmdline;
mod rotate_reference;
@@ -158,12 +158,10 @@ mod setvar_coverage;
mod shapes;
mod snap_annotations;
mod snap_blocks;
mod snap_center_on_curve;
mod snap_curves;
mod snap_intersections_aperture;
mod snap_nearest;
mod snap_overrides;
mod snap_tab_cycling;
mod snap_tracking;
mod snaps_more;
mod solid_command;
@@ -1,9 +1,8 @@
//! DIST snaps to the model geometry displayed in paper-space viewports (#516).
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -279,46 +278,6 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
/// closer, as within one space a snap point beats Nearest. Tab starts at the click's snap and
/// still reaches the paper-space Nearest.
#[test]
fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
let (mut d, paper) = drawing();
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!(
all.iter().any(|h| h.mode == mode::NEA && h.viewport.is_none() && h.point.near(Vec2::new(94.7, 50.0), 1e-9)),
"Tab reaches the paper-space Nearest: {all:?}"
);
}
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
/// since DIST measures in the model units of the viewport picked.
#[test]
fn overlapping_viewports_each_offer_their_model_point() {
let (mut d, paper) = drawing();
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
EntityKind::Viewport(vp) => vp.clone(),
_ => panic!("viewport fixture"),
};
vp.view_center = Vec2::new(0.0, 0.0);
vp.id = 3;
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
let mut models: Vec<Vec2> =
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
models.sort_by(|a, b| a.x.total_cmp(&b.x));
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
}
#[test]
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
let (mut d, paper) = drawing();
@@ -430,50 +389,3 @@ fn malformed_and_paper_space_viewports_are_not_snap_sources() {
assert!(osnap(&d, &paper, Vec2::new(95.1, 50.1), 0.5, mode::END, None, false).is_none());
}
}
/// Nearest on a curve that leaves the viewport: the curve's closest point to the cursor is outside
/// the viewport, another point of it within the aperture is inside, and Nearest snaps there.
#[test]
fn nearest_takes_the_visible_part_of_a_curve_crossing_the_viewport_edge() {
let (mut d, paper) = drawing();
// The viewport shows model y up to 20. A tall ellipse peaks at (15, 20.1), just outside.
let ellipse = Ellipse { center: Vec3::new(15.0, 0.0, 0.0), major: Vec3::new(0.0, 20.1, 0.0), ratio: 0.1, start: 0.0, end: std::f64::consts::TAU };
d.add(&Space::Model, Common::default(), EntityKind::Ellipse(ellipse)).unwrap();
// The viewport's border is on a layer that is off, so it offers no Nearest of its own.
d.layers.push(cadcraft_engine::doc::Layer { name: "Border".into(), on: false, ..Default::default() });
let vp = viewport(&d, &paper);
d.modify_entity(vp, |e| e.common.layer = "Border".into()).unwrap();
// Model (15, 19.99): 0.11 from the peak, about 0.2 from where the ellipse comes back inside.
let cursor = Vec2::new(102.5, 59.995);
let hit = osnap(&d, &paper, cursor, 0.5, mode::NEA, None, false).expect("a visible nearest point");
let model = hit.viewport.expect("seen through the viewport").point;
assert!(model.y <= 20.0 + 1e-9 && model.dist(Vec2::new(15.0, 19.99)) <= 1.0, "{hit:?}");
}
#[test]
fn a_twisted_viewport_offers_the_visible_perpendicular_when_a_nearer_one_is_off_the_sheet() {
// A viewport twisted 45°, 20 square at 0,0 on the sheet, scale 1. Through it, a line along
// y = 0 under the cursor and one along x = 9.3 (sheet coordinates). From the base 12,3 the
// foot on the first, 12,0, is inside the turned model box but off the viewport; the foot on
// the second, 9.3,3, is on it.
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
let vp = Viewport {
center: Vec3::ZERO,
width: 20.0,
height: 20.0,
view_center: Vec2::ZERO,
view_height: 20.0,
id: 2,
twist: std::f64::consts::FRAC_PI_4,
..Viewport::default()
};
for (a, b) in [(Vec2::new(-9.0, 0.0), Vec2::new(30.0, 0.0)), (Vec2::new(9.3, -9.0), Vec2::new(9.3, 9.0))] {
let (a, b) = (vp.paper_to_model(a), vp.paper_to_model(b));
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })).unwrap();
}
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let hit = osnap(&d, &paper, Vec2::new(9.0, 0.0), 0.5, mode::PER, Some(Vec2::new(12.0, 3.0)), false).expect("the visible foot");
assert_eq!(hit.mode, mode::PER);
assert!(hit.point.near(Vec2::new(9.3, 3.0), 1e-9), "{hit:?}");
}
-23
View File
@@ -1,9 +1,7 @@
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
use cadcraft_engine::Input;
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use serde_json::json;
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
@@ -64,27 +62,6 @@ fn offset_multiple_and_undo() {
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
}
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
// (the distance between them) was rejected, and the second click had no distance guide.
#[test]
fn offset_distance_from_two_clicked_points() {
let mut s = one_line();
s.start("offset").unwrap();
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
let p = s.current_prompt().unwrap();
assert!(p.message.contains("second point"), "{}", s.prompt_text());
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
// The guide from the first click to the cursor is the previewed distance.
let guide = s.preview(Vec2::new(20.0, 22.5));
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
s.script("5,0 5,1\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
}
#[test]
fn offset_json_erase_and_layer() {
let mut s = one_line();
@@ -1,116 +0,0 @@
//! Running object snaps in a fresh drawing and in drawings opened from DXF and DWG files, with
//! AutoCAD's default modes (OSMODE 4133: Endpoint, Center, Intersection, Extension).
//!
//! Moving onto a circle, an arc or a polyline arc finds its Center. OSMODE is a profile setting,
//! as in AutoCAD (saved in the registry there, not the drawing): a file's `$OSMODE` header
//! variable, 0 included, never changes the running snaps.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::snap::{mode, tracking::CursorQuery};
use serde_json::json;
/// AutoCAD's default running snaps.
const DEFAULT: u32 = 4133;
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
/// A line crossed by another, a circle, an arc and a polyline with a straight and an arc segment.
fn draw(s: &mut Session) {
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
s.execute("line", &json!({ "points": [[5, -5], [5, 5]] })).unwrap();
s.execute("circle", &json!({ "center": [50, 0], "radius": 5 })).unwrap();
s.execute("arc", &json!({ "center": [80, 0], "radius": 5, "start": 0, "end": 180 })).unwrap();
// 100,0 to 110,0 straight, then a half circle (bulge 1) to 130,0 round 120,0, below the axis.
s.execute("pline", &json!({ "vertices": [[100, 0], {"p": [110, 0], "bulge": 1.0}, [130, 0]] })).unwrap();
}
fn drawing() -> Drawing {
let mut s = Session::new();
draw(&mut s);
s.doc().unwrap().clone()
}
/// Where a click at `cursor` lands while LINE asks for its first point (the drawing area's path).
fn snap(s: &mut Session, cursor: Vec2) -> Option<(Vec2, u32)> {
if s.running.is_none() {
s.start("line").unwrap();
}
let q = CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(cursor, &q);
r.snap.map(|h| (r.point, h.mode))
}
fn assert_snaps(s: &mut Session, what: &str) {
assert_eq!(s.settings.osmode, DEFAULT, "{what}: the running snaps are the profile's");
let cases = [
("the line's end", Vec2::new(20.2, 0.1), Vec2::new(20.0, 0.0), &[mode::END][..]),
("the lines' crossing", Vec2::new(5.2, 0.15), Vec2::new(5.0, 0.0), &[mode::INT][..]),
("the circle", polar(Vec2::new(50.0, 0.0), 5.3, 45.0), Vec2::new(50.0, 0.0), &[mode::CEN][..]),
("the arc", polar(Vec2::new(80.0, 0.0), 5.2, 90.0), Vec2::new(80.0, 0.0), &[mode::CEN][..]),
("the arc's end", Vec2::new(85.2, 0.1), Vec2::new(85.0, 0.0), &[mode::END][..]),
("the polyline's vertex", Vec2::new(110.2, 0.1), Vec2::new(110.0, 0.0), &[mode::END][..]),
("the polyline's arc", polar(Vec2::new(120.0, 0.0), 10.2, 270.0), Vec2::new(120.0, 0.0), &[mode::CEN][..]),
];
for (name, cursor, want, modes) in cases {
let (p, m) = snap(s, cursor).unwrap_or_else(|| panic!("{what}: no snap on {name}"));
assert!(modes.contains(&m), "{what}, {name}: mode {m}");
assert!(p.near(want, 1e-6), "{what}, {name}: {p:?}");
}
// Away from everything: nothing.
assert_eq!(snap(s, Vec2::new(35.0, 20.0)), None, "{what}");
// F3 off: nothing; on again: back.
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)), None, "{what}: F3 off");
s.execute("osnap", &json!({})).unwrap();
assert_eq!(snap(s, Vec2::new(20.2, 0.1)).map(|h| h.1), Some(mode::END), "{what}: F3 on");
}
#[test]
fn default_snaps_work_in_a_fresh_drawing() {
let mut s = Session::new();
draw(&mut s);
assert_snaps(&mut s, "fresh drawing");
}
/// `text` with `$OSMODE` set to `value` at the top of its header.
fn with_osmode(text: &str, value: u32) -> String {
let at = text.find("HEADER").expect("a header section") + "HEADER".len();
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
let (head, tail) = text.split_at(at);
format!("{head}{eol} 9{eol}$OSMODE{eol} 70{eol}{value}{tail}")
}
#[test]
fn a_dxf_with_osmode_0_keeps_the_running_snaps() {
let clean = String::from_utf8(cadcraft_io::write(&drawing(), "snaps.dxf").unwrap()).unwrap();
let text = with_osmode(&clean, 0);
let d = cadcraft_io::read(text.as_bytes(), "snaps.dxf").unwrap();
let mut s = Session::new();
// OSMODE is the profile's: the user's own choice survives opening the file.
s.execute("setvar", &json!({ "name": "OSMODE", "value": DEFAULT })).unwrap();
s.open_drawing(d, "snaps.dxf", None);
assert_snaps(&mut s, "DXF with $OSMODE 0");
// Nor does a file change a profile without Center.
let mut s = Session::new();
s.execute("setvar", &json!({ "name": "OSMODE", "value": mode::END })).unwrap();
let text = with_osmode(&clean, DEFAULT);
assert_eq!(text.matches("$OSMODE").count(), 1, "one $OSMODE in the file");
s.open_drawing(cadcraft_io::read(text.as_bytes(), "x.dxf").unwrap(), "x.dxf", None);
assert_eq!(s.settings.osmode, mode::END);
}
#[test]
fn default_snaps_work_in_a_drawing_opened_from_dwg() {
// The drawing is the test's own, so it is converted in this process.
cadcraft_io::dwg_worker::allow_in_process();
let bytes = cadcraft_io::write(&drawing(), "snaps.dwg").unwrap();
let d = cadcraft_io::read(&bytes, "snaps.dwg").unwrap();
let mut s = Session::new();
s.open_drawing(d, "snaps.dwg", None);
assert_snaps(&mut s, "DWG");
}
+1
View File
@@ -104,6 +104,7 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() {
explodable: true,
units: 0,
array: None,
xref_stamp: None,
};
d.blocks.insert("*D1".into(), std::sync::Arc::new(block));
d.model.modify(dim, |e| {
+3 -2
View File
@@ -279,7 +279,7 @@ fn interactive_refedit_refset_and_refclose() {
}
#[test]
fn xrefs_are_refused_with_a_message() {
fn an_xref_that_is_not_loaded_is_refused_with_a_message() {
let mut s = Session::new();
s.doc_mut().unwrap().blocks.insert(
"X".into(),
@@ -291,5 +291,6 @@ fn xrefs_are_refused_with_a_message() {
);
let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0);
let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err();
assert!(e.to_string().contains("external reference"), "{e}");
// Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be.
assert!(e.to_string().contains("not loaded"), "{e}");
}
File diff suppressed because it is too large Load Diff
@@ -1,202 +0,0 @@
//! Center snaps from the curve, as in AutoCAD: with the cursor over a circle, an arc, an
//! ellipse or a polyline arc (also inside a block reference) the running Center snap finds its
//! center, however far away it is. Before, the center was only found with the cursor on the
//! center itself, so moving onto a circle with the default running snaps (END, CEN, INT, EXT)
//! showed nothing.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, EntityKind, Insert, Space};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::{self, mode};
use serde_json::json;
/// AutoCAD's default running snaps (OSMODE 4133).
const DEFAULT: u32 = 4133;
fn snap_at(s: &Session, cursor: Vec2, aperture: f64, osmode: u32) -> Option<(Vec2, u32)> {
snap::osnap(s.doc().unwrap(), &Space::Model, cursor, aperture, osmode, None, false).map(|h| (h.point, h.mode))
}
fn polar(c: Vec2, r: f64, deg: f64) -> Vec2 {
let a = deg.to_radians();
c + Vec2::new(r * a.cos(), r * a.sin())
}
#[test]
fn cursor_on_a_circle_snaps_to_its_center() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [100, 50], "radius": 20 })).unwrap();
let c = Vec2::new(100.0, 50.0);
for deg in [10.0, 45.0, 130.0, 250.0, 300.0] {
// A hair off the circle, well inside the aperture; the center is 20 units away.
let cursor = polar(c, 20.3, deg);
let (p, m) = snap_at(&s, cursor, 1.0, DEFAULT).unwrap_or_else(|| panic!("no snap on the circle at {deg}°"));
assert_eq!(m, mode::CEN, "at {deg}°");
assert!(p.near(c, 1e-9), "at {deg}°: {p:?}");
}
// Away from the circle (outside the aperture) there is nothing.
assert_eq!(snap_at(&s, polar(c, 23.0, 45.0), 1.0, DEFAULT), None);
// Center off: no center.
assert_eq!(snap_at(&s, polar(c, 20.3, 45.0), 1.0, mode::END), None);
// On the center itself, as before.
assert_eq!(snap_at(&s, c + Vec2::new(0.2, 0.1), 1.0, DEFAULT).map(|h| h.1), Some(mode::CEN));
}
#[test]
fn arcs_ellipses_and_polyline_arcs_snap_to_their_centers() {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap();
s.execute("ellipse", &json!({ "center": [50, 0], "major": [8, 0], "ratio": 0.5 })).unwrap();
// A polyline with a half-circle bulge from (100,0) to (120,0): center (110,0), radius 10.
s.execute("pline", &json!({ "vertices": [{"p": [100, 0], "bulge": 1.0}, [120, 0]] })).unwrap();
let arc = snap_at(&s, polar(Vec2::ZERO, 10.2, 45.0), 1.0, DEFAULT).unwrap();
assert_eq!(arc.1, mode::CEN);
assert!(arc.0.near(Vec2::ZERO, 1e-9));
// The arc runs 0°-90°: on its circle at 200° (not on the arc) there is no center.
assert_eq!(snap_at(&s, polar(Vec2::ZERO, 10.2, 200.0), 1.0, DEFAULT), None);
let el = snap_at(&s, Vec2::new(50.0, 4.2), 1.0, DEFAULT).unwrap();
assert_eq!(el.1, mode::CEN);
assert!(el.0.near(Vec2::new(50.0, 0.0), 1e-9));
let pl = snap_at(&s, polar(Vec2::new(110.0, 0.0), 10.2, 270.0), 1.0, DEFAULT).unwrap();
assert_eq!(pl.1, mode::CEN, "the bulge's arc");
assert!(pl.0.near(Vec2::new(110.0, 0.0), 1e-9), "{:?}", pl.0);
}
#[test]
fn a_nearer_endpoint_or_intersection_still_wins() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("line", &json!({ "points": [[10, 0], [30, 0]] })).unwrap();
// At the line's end on the circle: Endpoint/Intersection, not the far center.
let (p, m) = snap_at(&s, Vec2::new(10.2, 0.1), 1.0, DEFAULT).unwrap();
assert!(m == mode::END || m == mode::INT, "{m}");
assert!(p.near(Vec2::new(10.0, 0.0), 1e-9));
}
#[test]
fn circles_inside_block_references_snap_to_their_centers() {
let mut s = Session::new();
let c = s.execute("circle", &json!({ "center": [5, 0], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string();
s.execute("block", &json!({ "name": "H", "base": [0, 0], "handles": [c], "keep": "delete" })).unwrap();
let kind = EntityKind::Insert(Insert {
block: "H".into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(3.0, 3.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
});
s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap();
// The circle lands at (115,100) with radius 6.
let (p, m) = snap_at(&s, polar(Vec2::new(115.0, 100.0), 6.2, 60.0), 1.0, DEFAULT).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(115.0, 100.0), 1e-9), "{p:?}");
}
#[test]
fn tab_cycling_offers_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
let all = snap_candidates(s.doc().unwrap(), &Space::Model, polar(Vec2::ZERO, 10.2, 30.0), 1.0, DEFAULT, None, false);
assert_eq!(all.iter().filter(|h| h.mode == mode::CEN && h.point.near(Vec2::ZERO, 1e-9)).count(), 1, "{all:?}");
}
#[test]
fn the_cursor_query_snaps_to_the_center_from_the_curve() {
// The path the drawing area uses (Session::snap_cursor): the point a click would take.
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 50 })).unwrap();
s.start("line").unwrap();
let q = snap::tracking::CursorQuery { base: None, deferred: true, corner: false, aperture: 1.0, tol: 0.5, now: 0.0, shift: false };
let r = s.snap_cursor(polar(Vec2::ZERO, 50.4, 33.0), &q);
assert_eq!(r.snap.map(|h| h.mode), Some(mode::CEN));
assert!(r.point.near(Vec2::ZERO, 1e-9), "{:?}", r.point);
}
/// The arc of the review of #2347 (and #1114's test): center (100,50), radius 80, 30°-150°.
fn review_arc() -> Session {
let mut s = Session::new();
s.execute("arc", &json!({ "center": [100, 50], "radius": 80, "start": 30, "end": 150 })).unwrap();
s
}
#[test]
fn a_midpoint_under_the_cursor_beats_the_center_from_the_curve() {
let s = review_arc();
// On the arc's midpoint (100,130) with Center and Midpoint running: Midpoint, as in AutoCAD.
for cursor in [Vec2::new(100.05, 130.0), Vec2::new(100.2, 130.1)] {
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
assert_eq!(snap_at(&s, cursor, 0.5, mode::MID), Some((Vec2::new(100.0, 130.0), mode::MID)), "at {cursor:?}");
}
// Elsewhere on the arc, with no snap point in the aperture, the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(100.0, 50.0), 80.1, 70.0), 0.5, mode::CEN | mode::MID).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(100.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_quadrant_under_the_cursor_beats_the_center_from_the_curve() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [20, 0], "radius": 2 })).unwrap();
let cursor = Vec2::new(20.1, 2.0);
assert_eq!(snap_at(&s, cursor, 0.5, mode::CEN | mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
assert_eq!(snap_at(&s, cursor, 0.5, mode::QUA), Some((Vec2::new(20.0, 2.0), mode::QUA)));
// Away from the quadrants the center from the curve.
let (p, m) = snap_at(&s, polar(Vec2::new(20.0, 0.0), 2.1, 45.0), 0.5, mode::CEN | mode::QUA).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(20.0, 0.0), 1e-9), "{p:?}");
}
#[test]
fn many_straight_segments_do_not_hide_a_circle_from_center() {
// A polyline of 2,500 straight segments zigzagging over the cursor, then a circle: the
// work limit counts circles and arcs only, so the circle's center is still found.
let mut s = Session::new();
let vertices: Vec<[f64; 2]> = (0..=2500).map(|i| [i as f64 * 0.04, if i % 2 == 0 { 0.0 } else { 100.0 }]).collect();
s.execute("pline", &json!({ "vertices": vertices })).unwrap();
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
let (p, m) = snap_at(&s, polar(Vec2::new(50.0, 50.0), 20.2, 100.0), 0.5, mode::CEN).unwrap();
assert_eq!(m, mode::CEN);
assert!(p.near(Vec2::new(50.0, 50.0), 1e-9), "{p:?}");
}
#[test]
fn a_viewport_center_keeps_its_curve_distance_against_paper_space() {
use cadcraft_engine::doc::{Circle, Drawing, Viewport};
let mut d = Drawing::new_imperial();
let paper = Space::Paper("Layout1".into());
// Model circle (10,0) r16 seen through a viewport at half scale: paper center (100,50), radius 8.
d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(10.0, 0.0, 0.0), radius: 16.0 })).unwrap();
let vp = Viewport {
center: Vec3::new(100.0, 50.0, 0.0),
width: 20.0,
height: 20.0,
view_center: Vec2::new(10.0, 0.0),
view_height: 40.0,
id: 2,
locked: false,
frozen_layers: Vec::new(),
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
};
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
// A small paper-space circle whose curve passes 0.3 from the cursor and whose center is
// nearer the cursor (3.3) than the model circle's (8).
d.add(&paper, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(108.0, 53.3, 0.0), radius: 3.0 })).unwrap();
// The cursor is on the model circle (0.1 off in paper units): its center wins.
let h = snap::osnap(&d, &paper, Vec2::new(108.1, 50.0), 0.5, mode::CEN, None, false).unwrap();
assert_eq!(h.mode, mode::CEN);
assert!(h.point.near(Vec2::new(100.0, 50.0), 1e-9), "{h:?}");
assert!(h.viewport.is_some());
// On the paper circle, away from the model one: its center.
let h = snap::osnap(&d, &paper, Vec2::new(108.0, 56.35), 0.5, mode::CEN, None, false).unwrap();
assert!(h.point.near(Vec2::new(108.0, 53.3), 1e-9), "{h:?}");
assert!(h.viewport.is_none());
}
-28
View File
@@ -70,9 +70,6 @@ fn elliptical_arc_perpendicular_and_tangent_from_a_base_point() {
let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
assert_eq!(m, mode::TAN);
assert!(on_quarter(q) && Vec2::new(q.x / 16.0, q.y / 4.0).dot(q - base).abs() < 1e-9, "{q:?}");
// The same tangent at a prompt that resolves deferred snaps (CIRCLE's 3P points, #1512).
let h = snap::osnap(s.doc().unwrap(), &Space::Model, q, 0.3, mode::TAN, Some(base), true).expect("tangent at a deferred prompt");
assert!(h.mode == mode::TAN && h.deferred.is_none() && h.point.near(q, 1e-9), "{h:?}");
// Perpendicular from (10,10): the line from the base runs along the normal.
let base = Vec2::new(10.0, 10.0);
let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
@@ -122,28 +119,3 @@ fn spline_midpoint_perpendicular_and_tangent() {
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized();
assert!(d.cross((q - base).normalized()).abs() < 1e-3, "the line from the base runs along the curve at {q:?}");
}
#[test]
fn perpendicular_from_an_arcs_center_stays_on_the_arc() {
// From the center of an arc every point is perpendicular: the one under the cursor, never a
// point of its circle outside the sweep.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [0, 0], "radius": 10, "start": 90, "end": 180})).unwrap();
let hit = snap::osnap(s.doc().unwrap(), &Space::Model, Vec2::new(-6.0, 8.0), 0.3, mode::PER, Some(Vec2::ZERO), false);
let (p, m) = hit.map(|h| (h.point, h.mode)).expect("a perpendicular on the arc");
assert_eq!(m, mode::PER);
assert!(p.near(Vec2::new(-6.0, 8.0), 1e-9), "{p:?}");
}
#[test]
fn perpendicular_to_a_ray_needs_the_cursor_on_the_ray() {
// A ray along +X from the origin: behind its start the cursor is over nothing.
let mut s = Session::new();
s.execute("ray", &serde_json::json!({"base": [0, 0], "through": [10, 0]})).unwrap();
let d = s.doc().unwrap();
let base = Some(Vec2::new(5.0, 3.0));
assert_eq!(snap::osnap(d, &Space::Model, Vec2::new(-2.0, 0.0), 0.5, mode::PER, base, false), None);
// Over the ray, the foot is found.
let hit = snap::osnap(d, &Space::Model, Vec2::new(2.0, 0.0), 0.5, mode::PER, base, false).expect("the foot on the ray");
assert!(hit.point.near(Vec2::new(5.0, 0.0), 1e-9), "{hit:?}");
}
-122
View File
@@ -21,17 +21,6 @@ fn last_line(s: &Session) -> (Vec2, Vec2) {
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).last().unwrap()
}
/// The last circle drawn as (center, radius).
fn last_circle(s: &Session) -> (Vec2, f64) {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some((c.center.xy(), c.radius)) } else { None })
.last()
.unwrap()
}
fn near(p: Vec2, x: f64, y: f64) -> bool {
p.near(Vec2::new(x, y), 1e-9)
}
@@ -91,23 +80,6 @@ fn nothing_to_snap_to_rejects_the_point() {
assert!(near(s.last_point, 10.0, 10.0));
}
/// #2800: a typed PER or TAN finds its point from a pick anywhere on the object, as in AutoCAD.
/// The pick used to have to land within the aperture (0.125 here) of the foot or tangent point,
/// which you can't know in advance; elsewhere it said "No Perpendicular found".
#[test]
fn typed_per_and_tan_snap_from_anywhere_on_the_object() {
let mut s = drawing();
// From (5,5), PER picked at (3,0) on the line 0,0–10,0: two units from the foot (5,0).
s.script("LINE 5,5 PER 3,0\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 5.0, 5.0) && near(b, 5.0, 0.0), "{a:?} {b:?}");
// From (30,20), TAN picked at the top of the circle (centre 20,20, radius 3): the tangent
// points are at cos = 3/10 from the line to the base, and the upper one is nearer the pick.
s.script("LINE 30,20 TAN 20,23\n\n").unwrap();
let (a, b) = last_line(&s);
assert!(near(a, 30.0, 20.0) && near(b, 20.9, 20.0 + 3.0 * 0.91f64.sqrt()), "{a:?} {b:?}");
}
#[test]
fn from_nests_with_a_snap_override() {
let mut s = drawing();
@@ -144,97 +116,3 @@ fn a_command_keyword_wins_over_a_snap_word() {
s.cmdline("arc _cen").unwrap();
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text());
}
#[test]
fn tan_for_a_circle_radius_touches_the_picked_circle() {
// #1512: the circle around the center that touches the circle at 20,20 radius 3, on the side
// it was picked: the near side (radius 7), the far side (13), and through Diameter.
for (script, center, r) in [
("CIRCLE 30,20 TAN 23.02,20.03\n", (30.0, 20.0), 7.0),
("CIRCLE 30,20 TAN 16.98,19.97\n", (30.0, 20.0), 13.0),
("CIRCLE 20,10 D TAN 20.03,17.02\n", (20.0, 10.0), 7.0),
] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, got) = last_circle(&s);
assert!(near(c, center.0, center.1) && (got - r).abs() < 1e-9, "{script}: {c:?} r={got}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_the_picked_circles() {
// #1512: through two points and tangent to the circle at 20,20 radius 3, the tangent pick
// first or last.
for script in ["CIRCLE 3P 26,20 26,26 TAN 23.02,20.03\n", "CIRCLE 3P TAN 23.02,20.03 26,20 26,26\n"] {
let mut s = drawing();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(26.0, 20.0)) - r).abs() < 1e-9 && (c.dist(Vec2::new(26.0, 26.0)) - r).abs() < 1e-9, "{script}");
assert!((c.dist(Vec2::new(20.0, 20.0)) - (3.0 + r)).abs() < 1e-9, "{script}: {c:?} r={r}");
}
// Tan, Tan, Tan: the circle between three circles of radius 1, picked on their inner sides.
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 6,0 1\nCIRCLE 3,5 1\nCIRCLE 3P TAN 0.98,0.2 TAN 5.02,0.2 TAN 3.01,3.98\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
for k in [(0.0, 0.0), (6.0, 0.0), (3.0, 5.0)] {
assert!((c.dist(Vec2::new(k.0, k.1)) - (1.0 + r)).abs() < 1e-9, "{c:?} r={r}");
}
}
#[test]
fn tan_for_a_3p_circle_touches_an_arc_within_its_sweep() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// on the right or the far left, both off an arc swept from 90° to 100°: no circle.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 90, "end": 100})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 19.74,22.99\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(!s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Circle(_))));
}
#[test]
fn tan_for_a_3p_circle_takes_the_solution_that_touches_the_arc() {
// #1512: through 26,20 and 26,26, the circles tangent to the circle at 20,20 radius 3 touch it
// at about 29.6° and -103.3°. Picked at 20° on an arc swept from 200° to 25°, the 29.6°
// circle is nearer the pick but off the arc: the -103.3° one (radius 6.0826) is drawn.
let mut s = Session::new();
s.execute("arc", &serde_json::json!({"center": [20, 20], "radius": 3, "start": 200, "end": 25})).unwrap();
s.script("CIRCLE 3P 26,20 26,26 TAN 22.82,21.03\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!((c.dist(Vec2::new(20.0, 20.0)) - (r - 3.0)).abs() < 1e-9 && (r - 6.082575694955838).abs() < 1e-9, "{c:?} r={r}");
}
#[test]
fn tan_for_a_circle_radius_refuses_the_picked_circles_own_center() {
// #1512: a circle around 20,20 would lie on the circle there, not touch it.
let mut s = drawing();
s.script("CIRCLE 20,20 TAN 23.02,20.03\n").unwrap();
assert!(s.prompt_text().contains("radius of circle"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("No circle around the center is tangent there.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_refuses_the_picked_circle_itself() {
// #1512: tangent twice to the circle and through a point on it is only the circle itself.
let mut s = drawing();
s.script("CIRCLE 3P TAN 23.02,20.03 TAN 16.98,20.03 20,23\n").unwrap();
assert!(s.prompt_text().contains("third point"), "{}", s.prompt_text());
assert!(s.log.iter().any(|l| l.contains("Circle does not exist.")), "{:?}", s.log);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count(), 1);
}
#[test]
fn tan_for_a_3p_circle_through_points_in_line_with_the_picked_circles_center() {
// Through 3,0 and 5,0 and tangent to the unit circle at the origin: the two points and that
// circle's center lie on one line, the circle that touches it does not (center 4,±√48, radius 7).
let mut s = Session::new();
s.script("CIRCLE 0,0 1\nCIRCLE 3P 3,0 5,0 TAN 1,0\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let (c, r) = last_circle(&s);
assert!(near(Vec2::new(c.x, c.y.abs()), 4.0, 48f64.sqrt()) && (r - 7.0).abs() < 1e-9, "{c:?} r={r}");
}
-102
View File
@@ -1,102 +0,0 @@
//! Tab cycling through object snaps: a crowd of candidates is capped, hostile cursors and
//! apertures give no candidates, and the list never repeats a snap.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Space;
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::pointmod::snap_candidates;
use cadcraft_engine::snap::mode;
use serde_json::json;
#[test]
fn a_crowd_of_snaps_is_capped_and_never_repeats() {
let mut s = Session::new();
// 600 short lines fanning out from points packed round the origin: 1,200 endpoints.
for i in 0..600 {
let a = f64::from(i) * 0.01;
let p = [1e-3 * a.cos(), 1e-3 * a.sin()];
s.execute("line", &json!({ "points": [p, [a.cos(), a.sin()]] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::ZERO, 0.5, mode::END | mode::INT | mode::NEA, None, false);
assert!(!cands.is_empty());
assert!(cands.len() <= 257, "{} candidates", cands.len());
for (i, a) in cands.iter().enumerate() {
assert!(a.point.is_finite());
assert!(!cands.iter().skip(i + 1).any(|b| b.mode == a.mode && b.point == a.point), "{a:?} repeats");
}
}
#[test]
fn hostile_cursor_and_aperture_give_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let space = Space::Model;
let all = mode::END | mode::MID | mode::INT | mode::NEA | mode::PER;
for (c, ap) in [
(Vec2::new(f64::NAN, 0.0), 0.5),
(Vec2::new(0.0, f64::INFINITY), 0.5),
(Vec2::ZERO, f64::NAN),
(Vec2::ZERO, 0.0),
(Vec2::ZERO, -1.0),
(Vec2::ZERO, f64::INFINITY),
] {
assert!(snap_candidates(d, &space, c, ap, all, None, false).is_empty(), "{c:?} {ap}");
assert!(snap_candidates(d, &space, c, ap, all, Some(Vec2::new(f64::NAN, 1.0)), true).is_empty(), "{c:?} {ap}");
}
// A huge but finite aperture still answers, from the objects there are.
let far = snap_candidates(d, &space, Vec2::ZERO, 1e300, mode::END, None, false);
assert!(far.iter().all(|h| h.point.is_finite()));
// Object snaps off (or only the OFF bit) offer nothing.
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, 0, None, false).is_empty());
assert!(snap_candidates(d, &space, Vec2::ZERO, 0.5, mode::END | mode::OFF, None, false).is_empty());
}
#[test]
fn every_endpoint_under_the_aperture_is_offered_not_one_per_mode() {
let mut s = Session::new();
// Three line ends close together, all within the aperture of the cursor between them.
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
let d = s.doc().unwrap();
let cands = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false);
let ends: Vec<Vec2> = cands.iter().filter(|h| h.mode == mode::END).map(|h| h.point).collect();
assert_eq!(ends.len(), 3, "{cands:?}");
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(ends.iter().any(|p| p.near(want, 1e-12)), "{want:?} in {ends:?}");
}
// The first is the snap a click would take.
let first = snap_candidates(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).first().map(|h| h.point);
assert_eq!(first, cadcraft_engine::snap::osnap(d, &Space::Model, Vec2::new(0.03, 0.0), 0.125, mode::END, None, false).map(|h| h.point));
}
/// A base point that is not a number gives no candidates, though the cursor is on an endpoint: the
/// perpendicular and tangent points from it would be meaningless, as a viewport already treats it.
#[test]
fn a_non_finite_base_gives_no_candidates() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
let d = s.doc().unwrap();
let all = mode::END | mode::PER | mode::TAN | mode::NEA;
for base in [Vec2::new(f64::NAN, 1.0), Vec2::new(1.0, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NAN)] {
assert!(snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), false).is_empty(), "{base:?}");
assert!(cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(base), true).is_empty(), "{base:?}");
}
// A finite base still offers them.
assert!(!snap_candidates(d, &Space::Model, Vec2::new(10.01, 0.0), 0.5, all, Some(Vec2::new(5.0, 5.0)), false).is_empty());
}
#[test]
fn deferred_snaps_of_two_curves_at_one_point_are_both_offered() {
// Two circles touching at the origin: each offers its own deferred tangent there, and the
// line drawn from it depends on which circle it is.
let mut s = Session::new();
s.script("CIRCLE 0,1 1\nCIRCLE 0,-2 2\n").unwrap();
let d = s.doc().unwrap();
let all = cadcraft_engine::snap::osnap_all(d, &Space::Model, Vec2::new(0.0, 0.1), 0.5, mode::TAN, None, true);
let curves: Vec<_> = all.iter().filter_map(|h| h.deferred.map(|f| f.curve)).collect();
assert_eq!(curves.len(), 2, "{all:?}");
assert_ne!(curves.first(), curves.get(1), "{all:?}");
}
+33
View File
@@ -305,3 +305,36 @@ fn drawings_sharing_a_name_keep_their_own_backups() {
assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak");
assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak");
}
/// REFCLOSE Save writes an xref back the way SAVE writes a drawing: with ISAVEBAK off it keeps
/// no `.bak` (and reports none), with it on it keeps the previous file.
#[test]
fn an_xref_written_back_by_refclose_keeps_a_backup_as_save_does() {
let _g = saving();
hooks();
let dir = temp_dir("refclose");
let site = dir.join("site.dxf");
let mut x = Session::new();
add_circle(&mut x, 0.0);
x.execute("saveas", &json!({ "path": site.to_string_lossy() })).unwrap();
let host = dir.join("host.dxf");
let mut s = Session::new();
s.execute("saveas", &json!({ "path": host.to_string_lossy() })).unwrap();
let insert = s.execute("xattach", &json!({ "path": "site.dxf", "at": [100, 0] })).unwrap()["handle"].as_str().unwrap().to_string();
let bak = backup_path(&site);
cadcraft_engine::autosave::set_isavebak(false);
s.execute("refedit", &json!({ "handle": insert })).unwrap();
add_circle(&mut s, 110.0);
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!(circles(&site), 2, "the edit is written");
assert!(out["backup"].is_null() && !bak.exists(), "ISAVEBAK off keeps no backup: {out}");
cadcraft_engine::autosave::set_isavebak(true);
s.execute("refedit", &json!({ "handle": insert })).unwrap();
add_circle(&mut s, 120.0);
let out = s.execute("refclose", &json!({ "option": "save" })).unwrap();
assert_eq!((circles(&site), circles(&bak)), (3, 2), "{out}");
assert_eq!(files(&dir), ["host.dxf", "site.dxf", "site.dxf.bak"], "no staging files are left");
let _ = std::fs::remove_dir_all(&dir);
}
-196
View File
@@ -1,196 +0,0 @@
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
//!
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
//! the character map ranges and the metrics a font records stay at the caller that needs them.
fn be16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn be32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A simple glyph, with the point and contour counts `maxp` records for the font.
pub struct Glyph {
bytes: Vec<u8>,
points: usize,
contours: usize,
}
/// `.notdef`: no contours, no bytes.
pub fn notdef() -> Glyph {
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
}
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
let mut g = Vec::new();
be16(&mut g, contours.len() as u16);
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
for v in [box_.0, box_.1, box_.2, box_.3] {
be16(&mut g, v as u16);
}
let mut end = 0u16;
for c in contours {
end = end.saturating_add(c.len() as u16);
be16(&mut g, end.saturating_sub(1));
}
be16(&mut g, 0);
g.extend(std::iter::repeat_n(1u8, points.len()));
let (mut px, mut py) = (0i16, 0i16);
for (x, _) in &points {
be16(&mut g, x.wrapping_sub(px) as u16);
px = *x;
}
for (_, y) in &points {
be16(&mut g, y.wrapping_sub(py) as u16);
py = *y;
}
while g.len() % 4 != 0 {
g.push(0);
}
Glyph { bytes: g, points: points.len(), contours: contours.len() }
}
/// What the callers differ in; every other table field is the same in each font this builds.
pub struct Sfnt<'a> {
/// `glyf` entries, `.notdef` first.
pub glyphs: &'a [Glyph],
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
/// code. The `0xFFFF` segment that ends the map is added here.
pub cmap: &'a [(u16, u16, i16)],
/// The advance width every glyph shares, in em units.
pub advance: u16,
/// The left side bearing every glyph shares.
pub lsb: i16,
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
pub metrics: usize,
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
pub fs_type: u16,
/// `head`'s ink box: xMin, yMin, xMax, yMax.
pub ink_box: [i16; 4],
}
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
/// is a cap height of one unit.
const UNITS_PER_EM: u16 = 1000;
/// The font file `f` describes, as a TrueType file.
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
let mut glyf = Vec::new();
let mut loca = Vec::new();
for g in f.glyphs {
be32(&mut loca, glyf.len() as u32);
glyf.extend_from_slice(&g.bytes);
}
be32(&mut loca, glyf.len() as u32);
let mut head = Vec::new();
be32(&mut head, 0x0001_0000); // version
be32(&mut head, 0x0001_0000); // fontRevision
be32(&mut head, 0); // checkSumAdjustment
be32(&mut head, 0x5F0F_3CF5); // magic
be16(&mut head, 0); // flags
be16(&mut head, UNITS_PER_EM);
head.extend_from_slice(&[0; 16]); // created, modified
for v in f.ink_box {
be16(&mut head, v as u16);
}
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
// `u32`), glyphDataFormat.
for v in [0u16, 8, 2, 1, 0] {
be16(&mut head, v);
}
let mut hhea = Vec::new();
be32(&mut hhea, 0x0001_0000);
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut hhea, v as u16);
}
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
let mut maxp = Vec::new();
be32(&mut maxp, 0x0001_0000);
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
// the composite and instruction maxima after them.
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut maxp, v);
}
let mut hmtx = Vec::new();
for _ in 0..f.metrics {
be16(&mut hmtx, f.advance);
be16(&mut hmtx, f.lsb as u16);
}
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
// the caller's segments and the `0xFFFF` one that ends it.
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
let seg_count = segs.len() as u32;
let seg_selector = seg_count.ilog2();
let seg_search_range = 2 * (1 << seg_selector);
let mut sub = Vec::new();
be16(&mut sub, 4); // format
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
be16(&mut sub, 0); // language
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
be16(&mut sub, v);
}
for s in &segs {
be16(&mut sub, s.1);
}
be16(&mut sub, 0); // reservedPad
for s in &segs {
be16(&mut sub, s.0);
}
for s in &segs {
be16(&mut sub, s.2 as u16);
}
for _ in &segs {
be16(&mut sub, 0); // idRangeOffset
}
let mut cmap = Vec::new();
for v in [0u16, 1, 3, 1] {
be16(&mut cmap, v);
}
be32(&mut cmap, 12); // the subtable, straight after the records
cmap.extend_from_slice(&sub);
let mut os2 = vec![0u8; 78];
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
tables.sort_by_key(|t| *t.0);
let mut out = Vec::new();
be32(&mut out, 0x0001_0000); // sfnt version 1.0
let num_tables = tables.len() as u32;
let table_selector = num_tables.ilog2();
let dir_search_range = 16 * (1 << table_selector);
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
be16(&mut out, v);
}
let mut off = 12 + 16 * tables.len();
for (t, d) in &tables {
out.extend_from_slice(*t);
be32(&mut out, 0); // checkSum: the readers here do not verify it
be32(&mut out, off as u32);
be32(&mut out, d.len() as u32);
off += d.len().div_ceil(4) * 4;
}
for (_, d) in &tables {
out.extend_from_slice(d);
while out.len() % 4 != 0 {
out.push(0);
}
}
out
}
-24
View File
@@ -422,30 +422,6 @@ fn hostile_dxf_does_not_panic() {
}
}
// Regression test for #1336: the LAYER table of a DXF had no record cap, so a hostile file could
// grow the layer list without bound (its VIEW/UCS/VPORT peers stop at one million records).
#[test]
fn dxf_layer_table_stops_at_the_record_cap() {
use std::fmt::Write as _;
let records = 1_000_100;
let mut text = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n");
for i in 0..records {
let _ = write!(text, "0\nLAYER\n2\nL{i}\n");
}
text.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
let d = read(text.as_bytes(), "layers.dxf").unwrap();
// The exact total, not a range: the layer list stops at 1,000,000 layers, the drawing's own
// default layers counted among them, so a cap that truncates early or late fails as loudly as
// none at all. The count is a literal on purpose -- if the constant changes, this test must fail
// rather than follow it.
assert_eq!(
d.layers.len(),
1_000_000,
"the LAYER table must stop at exactly 1,000,000 layers in total, defaults included, reading {records} records, but kept {}",
d.layers.len()
);
}
#[test]
fn svg_and_png_export() {
let d = sample();
+2
View File
@@ -39,6 +39,8 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) {
explodable,
units,
array,
// Session state (when an xref was read), never in a file.
xref_stamp: _,
} = block.as_ref();
equal(name, &back.name, &path, "name");
equal(annotative, &back.annotative, &path, "annotative");
+128 -22
View File
@@ -3,8 +3,7 @@
//! rotation, width factor and obliquing; fonts whose licence bits forbid embedding, the stroke
//! font and the `text: "geometry"` option keep filled outlines.
//!
//! The fonts are tiny synthetic TrueType files built by the shared test helper in
//! `crates/fonts/tests/support/sfnt.rs` (no font files in the repository).
//! The fonts are tiny synthetic TrueType files built here (no font files in the repository).
use cadcraft_doc::{Common, Drawing, EntityKind, Space, Text, TextStyle, Viewport};
use cadcraft_geom::{Vec2, Vec3};
@@ -16,30 +15,137 @@ mod pdf_read;
use pdf_read::Doc;
// The synthetic TrueType file: the fonts layer's test-only helper, inlined rather than published
// or depended on.
#[path = "../../fonts/tests/support/sfnt.rs"]
mod sfnt;
// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ----------
fn be16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn be32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A simple glyph: one closed contour of on-curve points.
fn simple_glyph(pts: &[(i16, i16)]) -> Vec<u8> {
let mut g = Vec::new();
let xs: Vec<i16> = pts.iter().map(|p| p.0).collect();
let ys: Vec<i16> = pts.iter().map(|p| p.1).collect();
be16(&mut g, 1);
for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] {
be16(&mut g, v as u16);
}
be16(&mut g, pts.len() as u16 - 1);
be16(&mut g, 0);
g.extend(std::iter::repeat_n(1u8, pts.len()));
let (mut px, mut py) = (0i16, 0i16);
for (x, _) in pts {
be16(&mut g, (x - px) as u16);
px = *x;
}
for (_, y) in pts {
be16(&mut g, (y - py) as u16);
py = *y;
}
while g.len() % 4 != 0 {
g.push(0);
}
g
}
/// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds
/// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset.
/// `metrics` of the three metrics `hhea` declares.
fn test_font(fs_type: u16, metrics: usize) -> Vec<u8> {
sfnt::bytes(&sfnt::Sfnt {
// "A" is a triangle and "B" a square: one contour each.
glyphs: &[
sfnt::notdef(),
sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]),
sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]),
],
cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2
advance: 600,
lsb: 50,
metrics,
fs_type,
ink_box: [0, 0, 600, 700],
})
let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])];
let mut glyf = Vec::new();
let mut loca = Vec::new();
for g in &glyphs {
be32(&mut loca, glyf.len() as u32);
glyf.extend_from_slice(g);
}
be32(&mut loca, glyf.len() as u32);
let mut head = Vec::new();
be32(&mut head, 0x0001_0000);
be32(&mut head, 0x0001_0000);
be32(&mut head, 0);
be32(&mut head, 0x5F0F_3CF5);
be16(&mut head, 0);
be16(&mut head, 1000);
head.extend_from_slice(&[0; 16]);
for v in [0i16, 0, 600, 700] {
be16(&mut head, v as u16);
}
for v in [0u16, 8, 2, 1, 0] {
be16(&mut head, v);
}
let mut hhea = Vec::new();
be32(&mut hhea, 0x0001_0000);
for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut hhea, v as u16);
}
be16(&mut hhea, 3);
let mut maxp = Vec::new();
be32(&mut maxp, 0x0001_0000);
for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut maxp, v);
}
let mut hmtx = Vec::new();
for _ in 0..metrics {
be16(&mut hmtx, 600);
be16(&mut hmtx, 50);
}
// cmap: format 4, 'A'..'B' → 1..2.
let mut sub = Vec::new();
let segs: [(u16, u16, u16); 2] = [(0x41, 0x42, 1u16.wrapping_sub(0x41)), (0xFFFF, 0xFFFF, 1)];
be16(&mut sub, 4);
be16(&mut sub, (16 + segs.len() * 8) as u16);
be16(&mut sub, 0);
be16(&mut sub, (segs.len() * 2) as u16);
for v in [4u16, 1, 0] {
be16(&mut sub, v);
}
for s in segs {
be16(&mut sub, s.1);
}
be16(&mut sub, 0);
for s in segs {
be16(&mut sub, s.0);
}
for s in segs {
be16(&mut sub, s.2);
}
for _ in segs {
be16(&mut sub, 0);
}
let mut cmap = Vec::new();
for v in [0u16, 1, 3, 1] {
be16(&mut cmap, v);
}
be32(&mut cmap, 12);
cmap.extend_from_slice(&sub);
let mut os2 = vec![0u8; 78];
os2[8..10].copy_from_slice(&fs_type.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
tables.sort_by_key(|t| *t.0);
let mut out = Vec::new();
be32(&mut out, 0x0001_0000);
for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] {
be16(&mut out, v);
}
let mut off = 12 + 16 * tables.len();
for (t, d) in &tables {
out.extend_from_slice(*t);
be32(&mut out, 0);
be32(&mut out, off as u32);
be32(&mut out, d.len() as u32);
off += d.len().div_ceil(4) * 4;
}
for (_, d) in &tables {
out.extend_from_slice(d);
while out.len() % 4 != 0 {
out.push(0);
}
}
out
}
/// Register the test fonts once: an embeddable one, one with a restricted licence, and one
+10
View File
@@ -58,6 +58,15 @@ fn shown_transparency(b: &mut Builder, ctx: &Ctx, e: &Entity, layer_transparency
own
}
/// While a reference is edited in place (REFEDIT), everything outside the working set is faded by
/// XFADECTL percent on screen: how much `e` fades (0 when it doesn't).
fn refedit_fade(b: &Builder, ctx: &Ctx, e: &Entity) -> u8 {
match b.fade {
Some(f) if !b.plotting && !f.working.contains(&if ctx.depth == 0 { e.handle } else { ctx.top }) => f.percent,
_ => 0,
}
}
fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
// A top-level annotative object draws at the view's annotation scale: a viewport's scale for
// model space seen through it, else the drawing's (CANNOSCALE in model space, 1:1 on paper).
@@ -81,6 +90,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
if !visible {
return;
}
let fade = fade.max(refedit_fade(b, ctx, e));
let own = shown_transparency(b, ctx, e, layer_transparency, fade);
// A plot style's linetype replaces the object's.
let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) {
+19
View File
@@ -130,6 +130,24 @@ struct Builder<'a> {
points: &'a std::sync::atomic::AtomicUsize,
/// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests).
max_points: usize,
/// While a reference is edited in place: what is drawn faded ([`Fade::of`]).
fade: Option<&'a Fade>,
}
/// While a reference is edited in place (REFEDIT), everything outside the working set is drawn
/// faded by XFADECTL percent on screen. Built once per display list: a lookup per object drawn
/// would scan the working set each time.
struct Fade {
working: std::collections::HashSet<Handle>,
percent: u8,
}
impl Fade {
fn of(d: &Drawing) -> Option<Fade> {
let r = d.refedit.as_ref()?;
let percent = u8::try_from(d.header.i64("XFADECTL", 50).clamp(0, 90)).unwrap_or(50);
Some(Fade { working: r.items.iter().map(|i| i.copy).collect(), percent })
}
}
/// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy
@@ -370,6 +388,7 @@ impl<'a> Builder<'a> {
transparency: self.transparency,
points: self.points,
max_points: self.max_points,
fade: self.fade,
}
}
/// Take one unit of the block-expansion budget; false once it is spent, or once the build
+8 -3
View File
@@ -4,8 +4,8 @@ use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT};
use super::draw::entity;
use super::viewports::{MAX_VIEWPORTS, viewport};
use super::{
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen, plotstyle,
point,
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Fade, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen,
plotstyle, point,
};
/// Build options.
@@ -114,6 +114,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo
let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t));
let points = std::sync::atomic::AtomicUsize::new(0);
let fade = Fade::of(d);
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -124,6 +125,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo
transparency: 0,
points: &points,
max_points,
fade: fade.as_ref(),
};
if let Space::Paper(name) = space {
b.list.sheet = paper::sheet(d, name);
@@ -171,7 +173,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = store.iter().collect();
let budget = std::sync::atomic::AtomicUsize::new(0);
let (opts, plotting, points, max_points) = (b.opts, b.plotting, b.points, b.max_points);
let (opts, plotting, points, max_points, fade) = (b.opts, b.plotting, b.points, b.max_points, b.fade);
let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK)
.map(|chunk| {
@@ -185,6 +187,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
transparency: 0,
points,
max_points,
fade,
};
for e in chunk {
entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
@@ -238,6 +241,7 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
opts
};
let points = std::sync::atomic::AtomicUsize::new(0);
let fade = Fade::of(d);
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -248,6 +252,7 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
transparency: 0,
points: &points,
max_points: MAX_DISPLAY_POINTS,
fade: fade.as_ref(),
};
for e in ents {
entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
-68
View File
@@ -3,11 +3,6 @@ use crate::*;
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
use cadcraft_geom::{PolyVertex, Vec3};
// The synthetic TrueType file both this suite and the PDF writer's build: the fonts layer's
// test-only helper, inlined rather than published or depended on.
#[path = "../../fonts/tests/support/sfnt.rs"]
mod sfnt;
fn sample() -> Drawing {
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))
@@ -282,44 +277,6 @@ fn system_font() -> Option<&'static str> {
["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find(|n| cadcraft_fonts::ttf::find(n).is_some())
}
// ---------- a fixture TrueType font: no font file, no installed font ----------
/// A closed ellipse round (500, 350), wound by `clockwise`: one contour of a glyph outline.
fn ring(rx: f64, ry: f64, points: usize, clockwise: bool) -> Vec<(i16, i16)> {
let dir = if clockwise { -1.0 } else { 1.0 };
(0..points)
.map(|i| {
(
(500.0 + rx * (dir * std::f64::consts::TAU * i as f64 / points as f64).cos()) as i16,
(350.0 + ry * (dir * std::f64::consts::TAU * i as f64 / points as f64).sin()) as i16,
)
})
.collect()
}
/// A TrueType font whose only glyph, "O", is a 128-point ring: the flattened outline a real font's
/// curve gives, at the same scale, with plenty of detail to simplify. It is built in code so the
/// level-of-detail test needs no installed font and no font file in the repository (#651).
fn fixture_font() -> &'static str {
const NAME: &str = "cadcraft-render-lod.ttf";
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| cadcraft_fonts::ttf::register(NAME, fixture_font_bytes()));
NAME
}
fn fixture_font_bytes() -> Vec<u8> {
sfnt::bytes(&sfnt::Sfnt {
// Glyph 1 is "O": a 128-point ring, its counter a second, oppositely wound contour.
glyphs: &[sfnt::notdef(), sfnt::glyph(&[ring(500.0, 350.0, 128, false), ring(250.0, 150.0, 128, true)])],
cmap: &[(0x4F, 0x4F, 1 - 0x4F)], // "O" → glyph 1
advance: 1000, // one em wide
lsb: 0,
metrics: 2, // hmtx matches the two metrics hhea declares
fs_type: 0, // any use
ink_box: [0, 0, 1000, 700], // the ring's box; the 700-unit cap height is the unit scale
})
}
#[test]
fn truetype_text_is_filled_or_outlined() {
let Some(font) = system_font() else { return };
@@ -341,31 +298,6 @@ fn truetype_text_is_filled_or_outlined() {
assert!(l.prims.len() >= 3, "O has two contours, H one");
}
// Regression test for #651: filled TrueType text was triangulated at full outline detail at every
// zoom, so a page of small text on screen produced millions of triangles and froze the canvas.
#[test]
fn small_filled_text_on_screen_is_simplified_but_plots_keep_full_detail() {
let d = text_doc(fixture_font(), "OOOO");
let tris = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Tris).map(|p| l.points(p).len() / 3).sum::<usize>();
let plot = build_plot(&d, &Space::Model, &Options::default());
let full = tris(&plot);
assert!(full > 100, "a plot keeps every point of the 128-point rings: {full} triangles");
// One pixel is a tenth of the cap height: the rings are simplified to a few points, the shapes
// stay.
let reduced = build(&d, &Space::Model, &screen(0.1, None));
assert!(tris(&reduced) < full / 2, "{} triangles at 10 px per cap height, {full} in a plot", tris(&reduced));
assert!(tris(&reduced) > 0 && reduced.bounds.width() > plot.bounds.width() * 0.9, "{:?} vs {:?}", reduced.bounds, plot.bounds);
// An em under two pixels is drawn as the ink's box: two triangles a glyph, same extent.
let tiny = build(&d, &Space::Model, &screen(2.0, None));
assert_eq!(tris(&tiny), 2 * 4, "one box per glyph");
assert!(
tiny.bounds.width() > plot.bounds.width() * 0.9 && tiny.bounds.height() > plot.bounds.height() * 0.9,
"{:?} vs {:?}",
tiny.bounds,
plot.bounds
);
}
#[test]
fn missing_font_falls_back_to_stroke() {
let d = text_doc("NoSuchFontAnywhere.ttf", "OH");
-28
View File
@@ -256,34 +256,6 @@ mod tests {
assert!(tris.iter().all(|p| (5.0e5..=5.0e5 + 2.0).contains(&p.x) && (-3.0e5..=-3.0e5 + 2.0).contains(&p.y)));
}
// Regression test for #651: the level of detail followed the pixel size, so a page of small
// filled text on screen kept a few points a glyph while a plot kept all of them.
#[test]
fn a_small_on_screen_pixel_simplifies_glyphs_and_a_plot_does_not() {
// Text of height 1 has a 700-unit cap height: one font unit is 1/700 of a drawing unit.
let xf = Mat3 { a: 1.0 / 700.0, b: 0.0, c: 0.0, d: 1.0 / 700.0, e: 0.0, f: 0.0 };
assert!(matches!(detail(xf, 0.0), Detail::Full), "a plot keeps every point");
assert!(matches!(detail(xf, 2.0), Detail::Box), "an em under two pixels is the ink's box");
assert!(matches!(detail(xf, 0.1), Detail::Reduced(band) if band >= 2), "10 px per cap height simplifies");
assert!(matches!(detail(xf, f64::NAN), Detail::Full), "a pixel size that is not a size keeps full detail");
}
#[test]
fn a_coarse_band_drops_the_points_of_a_flattened_curve() {
// A ring of 64 points, the outline a flattened curve gives.
let ring: Vec<Vec2> = (0..64u32)
.map(|i| {
let t = std::f64::consts::TAU * f64::from(i) / 64.0;
Vec2::new(500.0 * t.cos(), 350.0 * t.sin())
})
.collect();
let coarse = simplify(&ring, 8.0);
assert!(coarse.len() < ring.len() / 2, "{} of {} points kept at 8 font units", coarse.len(), ring.len());
assert!(coarse.len() >= 4, "a ring never collapses to a line: {}", coarse.len());
let fine = simplify(&ring, 0.01);
assert!(fine.len() >= ring.len(), "a fine band keeps every point: {} of {}", fine.len(), ring.len());
}
#[test]
fn hostile_placed_outline_never_panics() {
assert!(triangulate_placed(&[]).is_empty());
+7 -3
View File
@@ -6,8 +6,8 @@ use super::draw::entity;
use super::pipeline::PARALLEL_CHUNK;
use super::pipeline::{Options, style_table, top_ctx, with_point_view};
use super::{
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper, pen,
plotstyle,
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Fade, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper,
pen, plotstyle,
};
/// Upper bound on viewports drawn per layout (hostile files).
@@ -71,6 +71,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t));
let points = std::sync::atomic::AtomicUsize::new(0);
let fade = Fade::of(d);
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -81,6 +82,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
transparency: 0,
points: &points,
max_points: MAX_DISPLAY_POINTS,
fade: fade.as_ref(),
};
contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle));
b.list
@@ -135,6 +137,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0,
points: b.points,
max_points: b.max_points,
fade: b.fade,
};
#[cfg(not(target_arch = "wasm32"))]
let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK;
@@ -146,7 +149,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
// As `build_parallel`: chunks built side by side, joined in drawing order.
use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = d.model.iter().collect();
let (opts, points, max_points) = (b.opts, b.points, b.max_points);
let (opts, points, max_points, fade) = (b.opts, b.points, b.max_points, b.fade);
let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK)
.map(|chunk| {
@@ -160,6 +163,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0,
points,
max_points,
fade,
};
let c = ctx();
for me in chunk.iter().filter(|me| seen(me)) {
+3
View File
@@ -1189,6 +1189,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
app.canvas.draw_ms = crate::now_ms() - t0;
compare::paint(app, ui.ctx(), painter, &xf_paper, rect);
blockedit::paint(app, ui.ctx(), painter, &xf_paper, rect);
refedit::paint(app, ui.ctx(), rect);
// Constraint bars and dynamic dimensional constraints (model space, or inside a viewport).
if sheet.is_none() || active_vp.is_some() {
let clip = match &active_vp {
@@ -1323,3 +1324,5 @@ mod compare;
/// Background rebuilds of the display list for a new view.
mod images;
mod rebuild;
/// The Edit Reference bar while a reference is edited in place (REFEDIT).
mod refedit;
+2 -4
View File
@@ -200,14 +200,12 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return };
let space = st.edit_space();
let frozen = st.viewport_frozen();
let hit = match cycle {
Some(i) => {
let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
cands.get(i % cands.len().max(1)).copied()
}
None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
};
let p = match (hit, app.canvas.snap) {
(Some(h), _) => {
+72
View File
@@ -0,0 +1,72 @@
//! Editing a reference in place (REFEDIT) on the canvas: a bar over the drawing with the
//! reference's name (and, for an xref, the file it writes to), the working set's size, Add to /
//! Remove from Working Set, and Save Changes / Discard Changes (REFCLOSE). The rest of the
//! drawing is drawn faded by the renderer (XFADECTL) and locked by the engine.
use egui::{Rect, RichText, Stroke, vec2};
use serde_json::json;
use crate::CadApp;
use crate::theme::Tokens;
fn id() -> egui::Id {
egui::Id::unique("cadcraft-refedit-bar")
}
/// The edit shown: (block, xref file, working-set size).
fn editing(app: &CadApp) -> Option<(String, Option<String>, usize)> {
let r = app.session.state().ok()?.doc.refedit.clone()?;
Some((r.block, r.xref.map(|x| x.file), r.items.len()))
}
/// What a bar button asks for.
enum Act {
Start(&'static str),
Run(&'static str, serde_json::Value),
}
/// The bar (over the drawing, at its top).
pub(super) fn paint(app: &mut CadApp, ctx: &egui::Context, rect: Rect) {
let Some((name, file, count)) = editing(app) else { return };
let t = Tokens::get();
let sel: Vec<String> = app.session.selection().iter().map(|h| h.hex()).collect();
let mut act = None;
egui::Area::new(id()).order(egui::Order::Foreground).pivot(egui::Align2::CENTER_TOP).fixed_pos(rect.center_top() + vec2(0.0, 8.0)).show(
ctx,
|ui| {
egui::Frame::new().fill(t.cmd_bg).stroke(Stroke::new(1.0, t.accent)).corner_radius(4.0).inner_margin(6.0).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(crate::tl!("Edit Reference")).color(t.accent).strong());
let shown = ui.label(RichText::new(&name).color(t.text));
if let Some(f) = &file {
shown.on_hover_text(crate::tf!("Saving writes {file}", file = f));
}
ui.label(RichText::new(crate::tf!("{n} in the working set", n = count)).color(t.text_dim));
ui.separator();
if ui.button(crate::tl!("Add to Working Set")).clicked() {
act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "add": sel })) });
}
if ui.button(crate::tl!("Remove from Working Set")).clicked() {
act = Some(if sel.is_empty() { Act::Start("refset") } else { Act::Run("refset", json!({ "remove": sel })) });
}
ui.separator();
if ui.button(RichText::new(crate::tl!("Save Changes")).color(t.accent)).clicked() {
act = Some(Act::Run("refclose", json!({ "option": "save" })));
}
if ui.button(crate::tl!("Discard Changes")).clicked() {
act = Some(Act::Run("refclose", json!({ "option": "discard" })));
}
});
});
},
);
match act {
Some(Act::Start(id)) => app.start(id),
Some(Act::Run(id, p)) => {
if let Err(e) = app.run(id, p) {
app.set_status(e);
}
}
None => {}
}
}
+6
View File
@@ -1367,6 +1367,12 @@ menu Modify Edita
Check for Updates… Verifica aggiornamenti…
CADCraft is up to date. CADCraft è aggiornato.
Could not check for updates. Impossibile verificare gli aggiornamenti.
Edit Reference Modifica riferimento
Saving writes {file} Il salvataggio scrive {file}
{n} in the working set {n} nel gruppo di lavoro
Remove from Working Set Rimuovi dal gruppo di lavoro
Save Changes Salva modifiche
Discard Changes Annulla modifiche
Add a drawing file as a block library Aggiungi un file di disegno come libreria di blocchi
Add a folder of drawings or a drawing file to use its blocks. Aggiungi una cartella di disegni o un file di disegno per usarne i blocchi.
Block Libraries Librerie di blocchi
1 # CADCraft Italian interface catalog — original translations by Emanuele Bottelli (AI-assisted, Claude).
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
+6
View File
@@ -1394,6 +1394,12 @@
Check for Updates… Перевірити оновлення…
CADCraft is up to date. Встановлено найновішу версію CADCraft.
Could not check for updates. Не вдалося перевірити оновлення.
Edit Reference Редагування посилання
Saving writes {file} Збереження записує {file}
{n} in the working set {n} у робочому наборі
Remove from Working Set Вилучити з робочого набору
Save Changes Зберегти зміни
Discard Changes Скасувати зміни
Save changes to block "{name}"? Зберегти зміни в блоці «{name}»?
Add a drawing file as a block library Додати файл креслення як бібліотеку блоків
Add a folder of drawings or a drawing file to use its blocks. Додайте теку з кресленнями або файл креслення, щоб використовувати його блоки.
Can't render this file because it contains an unexpected character in line 1403 and column 24.
+1
View File
@@ -683,6 +683,7 @@
Select an object to measure Select an object to measure
Add to Working Set 添加到工作集
Edit Reference In-Place 就地编辑参照
Reference Nesting Levels 参照嵌套级别
Save Reference Edits 保存参照编辑
Working Set 工作集
Xref and Block In-place Editing 外部参照和块的就地编辑
1 # CADCraft Simplified Chinese interface catalog — original translations.
683
684
685
686
687
688
689
-2
View File
@@ -27,7 +27,6 @@ mod mtext_double_click;
mod named_viewports_dialog;
mod native_menu_text_keys;
mod native_windows;
mod offset_clicks;
mod options_dialog;
mod options_right_click;
mod page_setup_paper_units;
@@ -43,7 +42,6 @@ mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod slow_clicks;
mod snap_tab_cycling;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
-83
View File
@@ -1,83 +0,0 @@
//! OFFSET on the canvas: the distance can be clicked, and picking the source is not moved by the
//! grid snap (#618).
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
fn harness() -> Harness<'static, CadApp> {
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec2::new(0.0, 2.0).to3(0.0), b: Vec2::new(10.0, 2.0).to3(0.0) })).unwrap();
let mut session = Session::empty();
session.open_drawing(d, "Offset clicks", None);
session.execute("view.set", &json!({"center":[5,5],"height":20})).unwrap();
session.settings.osmode = 0;
session.settings.snapmode = true;
session.execute("setvar", &json!({"name":"SNAPUNIT","value":[5,5]})).unwrap();
session.settings.orthomode = false;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
fn click(h: &mut Harness<'_, CadApp>, world: Vec2) {
let pos: Pos2 = h.state().canvas.xf.unwrap().to_screen(world);
h.event(Event::PointerMoved(pos));
h.run_steps(2);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
}
// Regression test for #618: OFFSET's distance could not be clicked, and with grid snap on a click
// meant to pick the source object was moved to the nearest grid point, missing the object.
#[test]
fn offset_takes_a_clicked_distance_and_picks_its_source_under_grid_snap() {
let mut h = harness();
h.state_mut().start("offset");
h.run_steps(2);
// Two clicks, snapped to the grid points (5, 5) and (10, 5): a distance of 5.
click(&mut h, Vec2::new(5.1, 4.9));
assert!(h.state().session.prompt_text().contains("second point"), "{}", h.state().session.prompt_text());
click(&mut h, Vec2::new(9.9, 5.1));
assert_eq!(h.state().session.doc().unwrap().header.f64("OFFSETDIST", -1.0), 5.0);
assert!(h.state().session.prompt_text().contains("Select object"), "{}", h.state().session.prompt_text());
// The source line is at y = 2, two units from the grid point (5, 0) the click would snap to.
click(&mut h, Vec2::new(7.0, 2.04));
let prompt = h.state().session.prompt_text();
assert!(prompt.contains("side to offset"), "the line was not picked: {prompt}");
// A side click above the line (snapped to (5, 5)) makes the copy 5 units up, at y = 7.
click(&mut h, Vec2::new(7.0, 7.0));
let lines: Vec<(f64, f64)> = h
.state()
.session
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(line) => Some((line.a.y, line.b.y)),
_ => None,
})
.collect();
assert_eq!(lines.len(), 2, "OFFSET added no line: {lines:?}");
assert!(lines.iter().any(|&(a, b)| (a - 7.0).abs() < 1e-9 && (b - 7.0).abs() < 1e-9), "no copy at y = 7: {lines:?}");
// OFFSET asks for the next object; Enter ends it.
assert!(h.state().session.prompt_text().contains("Select object to offset"), "{}", h.state().session.prompt_text());
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(h.state().session.prompt_text(), "Command:", "Enter ends OFFSET");
}
-136
View File
@@ -1,136 +0,0 @@
//! Tab at a point prompt steps through every object snap under the aperture (each endpoint of
//! each object nearby), not just the closest snap of each running mode, and comes back round.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::snap::mode;
use cadcraft_geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
#[test]
fn tab_cycles_through_every_endpoint_under_the_aperture() {
let mut s = Session::new();
// Three line ends close together (within the aperture of the cursor between them).
for (a, b) in [([0.0, 0.0], [10.0, 0.0]), ([0.06, 0.05], [0.06, 10.0]), ([0.03, -0.06], [-10.0, -10.0])] {
s.execute("line", &json!({ "points": [a, b] })).unwrap();
}
s.execute("setvar", &json!({ "name": "OSMODE", "value": 1 })).unwrap();
s.execute("view.set", &json!({ "center": [0, 0], "height": 20 })).unwrap();
let mut app = CadApp::new(s, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h.state_mut().session.start("line").unwrap();
h.run_steps(2);
let xf = h.state().canvas.xf.unwrap();
let at = xf.to_screen(Vec2::new(0.03, 0.0));
h.event(Event::PointerMoved(at));
h.run_steps(2);
let mut seen: Vec<Vec2> = Vec::new();
for i in 0..4 {
let p = h.state().canvas.snap.map(|s| s.point).unwrap();
if i < 3 {
assert!(!seen.iter().any(|q| q.near(p, 1e-9)), "Tab {i} repeats {p:?} ({seen:?})");
} else {
assert!(seen.first().is_some_and(|q| q.near(p, 1e-9)), "the fourth Tab comes back round");
}
seen.push(p);
h.event(Event::Text("\t".into()));
h.run_steps(2);
}
for want in [Vec2::new(0.0, 0.0), Vec2::new(0.06, 0.05), Vec2::new(0.03, -0.06)] {
assert!(seen.iter().any(|q| q.near(want, 1e-9)), "{want:?} in {seen:?}");
}
}
/// Three endpoints near 10,0: 10,0 (the nearest to the cursor), 10.03,0 and 9.95,0. Endpoint is
/// the only running snap, so every candidate is an endpoint.
fn three_ends() -> Harness<'static, CadApp> {
let mut d = Drawing::new_imperial();
for (a, b) in [((0.0, 0.0), (10.0, 0.0)), ((10.03, 0.0), (20.0, 0.0)), ((9.95, 0.0), (9.95, -5.0))] {
let line = Line { a: Vec2::new(a.0, a.1).to3(0.0), b: Vec2::new(b.0, b.1).to3(0.0) };
d.add(&Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
}
let mut session = Session::empty();
session.open_drawing(d, "Tab snap cycling", None);
session.execute("view.set", &json!({"center":[10,0],"height":8})).unwrap();
session.settings.osmode = mode::END;
session.settings.snapmode = false;
session.settings.orthomode = false;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h.state_mut().start("line");
h.run_steps(2);
assert_eq!(h.state().session.running.as_ref().unwrap().id, "line");
let ap = h.state().session.settings.aperture / h.state().canvas.xf.unwrap().scale;
assert!(ap > 0.07, "all three endpoints lie in the aperture ({ap})");
h
}
const CURSOR: Vec2 = Vec2::new(10.01, 0.0);
fn hover(h: &mut Harness<'_, CadApp>, p: Vec2) -> Pos2 {
let pos = h.state().canvas.xf.unwrap().to_screen(p);
h.event(Event::PointerMoved(pos));
h.run_steps(3);
pos
}
/// Tab, as the command line receives it (`cmdline::capture_tab`).
fn tab(h: &mut Harness<'_, CadApp>) {
h.event(Event::Text("\t".into()));
h.run_steps(3);
}
fn snapped(h: &Harness<'_, CadApp>) -> Vec2 {
let hit = h.state().canvas.snap.expect("a snap marker");
assert_eq!(hit.mode, mode::END);
hit.point
}
fn assert_at(got: Vec2, x: f64) {
assert!(got.near(Vec2::new(x, 0.0), 1e-9), "{got:?}, expected {x},0");
}
#[test]
fn moving_the_cursor_away_starts_the_cycle_over() {
let mut h = three_ends();
hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
hover(&mut h, Vec2::new(10.0, 2.0));
assert!(h.state().canvas.snap.is_none());
hover(&mut h, CURSOR);
assert_at(snapped(&h), 10.0);
}
#[test]
fn a_click_places_the_candidate_tab_chose() {
let mut h = three_ends();
let pos = hover(&mut h, CURSOR);
tab(&mut h);
assert_at(snapped(&h), 10.03);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
let base = h.state().session.current_prompt().and_then(|p| p.base).expect("LINE asks for the next point");
assert_at(base, 10.03);
}