Compare commits

..
37 Commits
Author SHA1 Message Date
Tanish Manku 7aaee29277 Tab snap tests: send Tab as the key press the command line reads now 2026-11-30 13:24:05 -07:00
Tanish Manku 334bcc3dc0 Tab snap tests: install the headless framework hook the app's frame now needs 2026-11-30 13:01:37 -07:00
Tanish Manku 3944964adf Merge main: gather_in takes main's skip handle and stays visible to tracking 2026-11-30 12:32:45 -07:00
Tanish Manku f8769d9650 Snap: rustfmt 2026-11-23 12:33:39 -07:00
Tanish Manku 0b2cfae274 Snap: Perpendicular to a ray needs the cursor on the ray
The 'cursor is over this object' distance measured a ray as a line both
ways, so a cursor behind the ray's start snapped to the foot on it. Measure
to the ray's own half; an xline stays two-sided.
2026-11-23 12:33:14 -07:00
Tanish Manku c647cb4eb9 Snap: a perpendicular from an arc's centre stays on the arc
From the centre every point of an arc is perpendicular. The snap passed the
base as the pick, so it fell back to a point of the arc's circle (10,0 for a
90-180 degree arc) outside the sweep. Take the point of the arc nearest the
cursor.
2026-11-23 12:31:37 -07:00
Tanish Manku 0314c8bf2a Snap: a twisted viewport offers its next snap when the best is off it
In a twisted viewport the model clip is the box round the turned viewport.
A perpendicular foot inside that box but off the viewport could win, and
view.hit then rejected it, so the click got no snap from the viewport while
Tab still offered a valid one. When the winner falls off the viewport, take
the best of the ranked others that is on it; the extra ranking runs only then.
2026-11-23 12:29:20 -07:00
Tanish Manku 71f4879f9c Tab: keep deferred snaps of different curves at one point
Two circles touching at the cursor each offer a deferred tangent at the same
provisional point. SnapHit::same took them for one snap and dropped the
second, so Tab could not pick the other circle. Compare the deferred curve.
2026-11-23 12:27:03 -07:00
Tanish Manku 472d3661ce CIRCLE 3P TAN: solve picks in line with the picked circle's centre
CIRCLE 3P 3,0 5,0 TAN on a unit circle at the origin found no circle: the
picks were collinear, so the only Newton start lay on y = 0 with every target
centre, and each step stayed on that line until the matrix went singular.
With collinear picks, also start from circles on both sides of their line.
2026-11-23 12:25:05 -07:00
Tanish Manku ca90388ff3 OSMODE test: build each DXF variant from the clean export
The second check added $OSMODE = 4133 to text that already had $OSMODE = 0,
so the file carried both. Build it from the clean export and assert one.
2026-11-23 12:23:04 -07:00
Tanish Manku ded4122de0 Merge main
#1673 (Tab cycles every candidate) is already carried by this stack: its
deferred_hits and tests were ported, and Tab's list comes from finish_all
ranked by Rank. Keep the stack's snap.rs, pointmod.rs and
measure_distance_snapping.rs; restore the first half of #1673's
osnap_all_ranks_every_candidate (snap points, then Nearest on each object).
2026-11-23 12:19:18 -07:00
Tanish Manku fe3b20a37a Merge main 2026-11-20 18:28:48 -07:00
Tanish Manku 9746b6999a Snap: rustfmt 2026-11-20 17:58:24 -07:00
Marco Arnulfo 0ca0af9026 Tab snap tests from #1408: moving away restarts the cycle, a click takes Tab's choice
Carried from #1408's crates/ui-egui/tests/tab_snap_cycling.rs onto the #2350
Tab list: moving_the_cursor_away_starts_the_cycle_over and
a_click_places_the_candidate_tab_chose, with their three-endpoint fixture.
2026-11-20 17:57:59 -07:00
Tanish Manku 6971715295 Tab: a base point that is not a number gives no candidates
With a finite cursor and aperture, a NaN or infinite base passed the Tab
list's guards and it still offered snaps, though the perpendicular and tangent
points from such a base mean nothing (a viewport already skips it).
osnap_all and snap_candidates now return none for it.
2026-11-20 17:51:37 -07:00
Tanish Manku 5bfba91aa8 Tab: every deferred tangent and perpendicular under the aperture
The Tab list took the one deferred snap a click would, so with a circle under
the cursor and no base point the deferred perpendicular could not be reached
after the deferred tangent, nor a second curve's deferred snap. The list now
has one deferred snap per curve and mode (ported from #1673), ranked after
the snap points; the click still takes the nearest. Makes
osnap_all_ranks_every_candidate (from #1673) pass.
2026-11-20 17:47:22 -07:00
Tanish Manku 080c96aa06 Tab: snaps seen through different viewports stay apart in the list
The Tab list dropped a snap as a repeat when another had the same mode and
paper point, so where two viewports overlap only one of their model points
could be picked, and DIST measures in the model units of the viewport picked.
A repeat now also has to come from the same viewport (and be deferred or not
alike), in osnap_all and in snap_candidates. Makes
overlapping_viewports_each_offer_their_model_point (from #1673) pass.
2026-11-20 17:45:11 -07:00
Oliver Hagmann a2f732118f Snap tests from #1673: Tab keeps each viewport's snap and every deferred snap
Carried from #1673 onto the #2350 Tab list: overlapping viewports each offer
their model point, the deferred tangent and perpendicular on one circle are
both offered, and a click across spaces. That last test is inverted from
#1673: with #2347's ranking a viewport Endpoint beats a paper-space Nearest
that scores closer, as a snap point beats Nearest within one space; Tab
starts at the click's snap and still reaches the Nearest.
2026-11-20 17:43:12 -07:00
Tanish Manku c2af11dfa7 Nearest: a curve crossing a viewport edge offers its visible point
The Nearest from #2350 took each object's closest point first and only then
dropped it when the viewport clipped it, so an ellipse or spline whose closest
point lay just outside the viewport offered nothing, though another of its
points was in the aperture and in view. Each segment's point is now checked
before the closest is chosen, as before #2350, in one helper the click snap
and the Tab list share.
2026-11-20 17:39:55 -07:00
Tanish Manku b1dcb46e08 Snap test: convert the test's own DWG in process, as main's DWG reader now asks 2026-11-20 17:37:04 -07:00
Tanish Manku c00bc59949 Snap tests: fill in the Insert clip and Viewport twist fields that main added after #2347 2026-11-20 17:28:59 -07:00
Tanish Manku 1b577e9eed Merge #3164: Snap: object snaps skip layers frozen in the active layout viewport
# Conflicts:
#	crates/engine/src/doc_state.rs
#	crates/engine/src/pointmod.rs
2026-11-20 17:27:48 -07:00
Tanish Manku 29bf02b6ce Merge #2103: CIRCLE: tangent snaps for the radius and for 3P points
# Conflicts:
#	crates/engine/src/snap.rs
2026-11-20 17:27:21 -07:00
Tanish Manku 1998da2643 Merge #2350: Tab cycles through every object snap under the aperture, not one per mode
# Conflicts:
#	crates/engine/src/snap.rs
#	crates/ui-egui/tests/it/main.rs
#	docs/gaps.md
#	docs/ui-parity.md
2026-11-20 17:26:58 -07:00
Tanish Manku 28ed9c58a7 Merge #2347: Object snap: Center found by moving onto a circle, arc, ellipse or polyline arc
# Conflicts:
#	crates/engine/src/snap.rs
#	docs/ui-parity.md
2026-11-20 17:23:44 -07:00
Tanish Manku a3560a1442 Merge #2825: PER and TAN snap from anywhere on the object 2026-11-20 17:23:11 -07:00
jayzed80 c40ff9603e Snap: skip VPLAYER-frozen layers in MSPACE (#3158) 2026-11-14 14:54:49 +00:00
ZachAR3 595ccf2b06 Merge remote-tracking branch 'origin/main' into circle-tan-radius
# Conflicts:
#	crates/engine/src/cmd/draw.rs
#	docs/ui-parity.md
2026-11-09 17:07:40 +01:00
austin62jakeandClaude Opus 5.5 8acdceeb61 fix(snap): a circle offers both perpendicular points from the base (CodeRabbit on #2825)
PER on a circle offered only the point nearest the base point, so with the
new object fallback a pick on the circle's far side jumped across it. Like
an arc, a circle now offers both antipodes, and the one nearer the cursor
wins. From the circle's centre, where every point is perpendicular, the
point under the cursor is taken.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 08:05:36 -06:00
austin62jakeandClaude Opus 5.5 4ce72c668a fix(snap): PER and TAN snap from anywhere on the object (#2800)
With a base point, a perpendicular or tangent snap was kept only when its
foot or tangent point lay within the aperture, so hovering elsewhere on the
line or circle found nothing, and a typed `per` said "No Perpendicular found
for specified point". As in AutoCAD, these snaps name an object, not a spot
on it: from anywhere over the object, the point jumps to the foot or the
tangent point.

They now also qualify when their object passes within the aperture, as a
fallback after every snap point within the aperture, so an endpoint,
midpoint or intersection under the cursor still wins. Of several objects,
the one nearest the cursor gives the snap; of several points on one (an
arc's antipodes, a circle's two tangents), the one nearest the cursor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 07:39:52 -06:00
Francesco BVandClaude Opus 5.5 55ec024e31 Object snap: the center from the curve ranks behind snap points
A center found from its curve was scored by the cursor's distance to the
curve, so it beat the Midpoint or Quadrant of the same curve under the
cursor (those lie on the curve), and they could only be picked with Tab.
Now finish() tries the curve centers only when no snap point is in the
aperture, as in AutoCAD: Endpoint, Midpoint, Quadrant and Intersection
under the cursor win, the center shows elsewhere on the curve.

Hits from layout viewports are compared with paper-space ones by the same
rank (tier, then the score scaled into paper units), so a center keeps
its curve distance there instead of being rescored by the distance to the
center point. The 2,000-item work limit counts circles, arcs and ellipses
only, so straight segments gathered before them can't hide them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-29 08:52:22 +01:00
Francesco BVandClaude Opus 5.5 64cb95d8ec Tab cycles through every object snap under the aperture, not one per mode (gaps U4)
Tab at a point prompt offered only the closest snap of each running mode,
so of several line ends under the aperture only one was reachable. The
candidate gathering is split out of osnap_in_with_prims (collect_in) and
the new snap::osnap_all keeps every candidate: each mode's points of every
object nearby, the intersections, perpendicular and tangent points from
the base, the deferred snap and the nearest point of each object, in
layout viewports too, ranked with the click snap's score (Nearest and
deferred last), without repeats and capped at 256. finish and finish_all
share base_snaps and nearest_points. pointmod::snap_candidates puts the
click snap first, then osnap_all's list.

Tests: every endpoint under the aperture is offered; 1,200 endpoints and
their crossings give at most 257 finite, unrepeated candidates; NaN or
infinite cursors, base points and apertures, zero or negative apertures,
OSMODE 0 and the F3 bit give none; with the real pointer Tab visits three
line ends and comes back round.

gaps: U4 removed. ui-parity: Tab row.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 19:52:55 +01:00
Francesco BVandClaude Opus 5.5 4a0063f5f6 Object snap: Center found by moving onto a circle, arc, ellipse or polyline arc
With the default running snaps (OSMODE 4133: END, CEN, INT, EXT) moving the
cursor onto a circle, an arc or the middle of a polyline arc found nothing:
Center only snapped with the cursor on the center itself. As in AutoCAD,
the cursor on a circle, arc, ellipse or polyline arc (also inside block
references) now finds its center (snap::curve_centers), scored by how near
the curve is so a nearer endpoint or intersection still wins; Tab cycling
offers it too.

Regression tests open DXF (with $OSMODE 0, which never changes the
profile's running snaps) and DWG files and snap on lines, intersections,
circles, arcs and polylines.

ui-parity: Center row.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-27 19:52:26 +01:00
ZachAR3 f4f0702d08 CIRCLE: a tangent circle never lies on the picked circle (#1512)
A radius picked with TAN around the picked circle's own center, or a 3P
circle tangent twice to one circle through a point on it, would only
reproduce that circle; both now report that no such circle exists.
2026-10-25 03:08:29 +01:00
ZachAR3 98401d6de2 CIRCLE: a 3P circle takes the tangent solution that touches the arc (#1512)
The arc check ran on the solver's best circle only, so when that one
touched the arc's circle off the sweep, a valid circle that touches the
arc was reported as nonexistent. The Tan, Tan, Tan solver now takes a
filter (ttt_where), and 3P skips off-arc candidates before choosing.
2026-10-25 02:47:57 +01:00
ZachAR3 97fbaf7da4 CIRCLE: keep ellipse and spline tangents, and touch an arc within its sweep (#1512)
At CIRCLE's deferred prompts only tangents to circles and arcs are
deferred; ellipses and splines keep the ordinary tangent from the base,
as before. A 3P circle solved for an arc's circle must touch the arc
itself: a circle that touches the arc's circle off the sweep is
refused with "Circle does not exist."
2026-10-25 02:14:02 +01:00
ZachAR3 90a239b410 CIRCLE: tangent snaps for the radius and for 3P points (fixes #1512)
At CIRCLE's radius and diameter prompts a TAN pick on a circle or arc
used the tangent point as seen from the center, which gives the wrong
radius, and the 3P points took a tangent as a plain point. These prompts
now take the tangent as deferred and CIRCLE resolves it:

- Radius or diameter: the circle around the center that touches the
  curve, on the side it was picked.
- 3P: the circle through the plain points that touches every curve
  picked with TAN, solved by the Tan, Tan, Tan solver (a plain point is
  a circle of radius zero). Three tangent picks give Tan, Tan, Tan.
  Points with no such circle report "Circle does not exist." and ask
  for the last point again.

A perpendicular from the base is still resolved from it, so PER keeps
giving a circle tangent to a line. Only prompts that ask for deferred
snaps change: LINE's have no base.
2026-10-25 00:22:55 +02:00
111 changed files with 2330 additions and 9822 deletions
Generated
+6 -6
View File
@@ -378,9 +378,9 @@ dependencies = [
[[package]] [[package]]
name = "async-executor" name = "async-executor"
version = "1.14.1" version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
dependencies = [ dependencies = [
"async-task", "async-task",
"concurrent-queue", "concurrent-queue",
@@ -2733,9 +2733,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.3" version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [ dependencies = [
"percent-encoding", "percent-encoding",
] ]
@@ -6609,9 +6609,9 @@ dependencies = [
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.9" version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [ dependencies = [
"form_urlencoded", "form_urlencoded",
"idna", "idna",
-43
View File
@@ -1,43 +0,0 @@
//! A LISP routine in a `run` script runs to its end before the script goes on and the drawing is
//! saved, however many slices it takes (#3635).
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The loop takes many slices: the circle drawn after it is in the saved drawing, and the next
/// line runs once the routine has ended.
#[test]
fn a_long_routine_in_a_script_draws_before_the_save() {
let scratch = Scratch::new("lisp-script");
let saved = scratch.0.join("out.dxf");
let saved = saved.to_str().unwrap();
let script = r#"(progn (repeat 1000000 (setq x 1)) (command "circle" "0,0" "5") (princ "done"))\n(princ (+ x 1))"#;
let out = cli(&["run", "--metric", "--script", script, "--save", saved]);
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{:?}: {err}", out.status);
assert!(err.lines().any(|l| l == "done") && err.lines().any(|l| l == "2"), "{err}");
let info = cli(&["info", saved]);
let v: serde_json::Value = serde_json::from_slice(&info.stdout).unwrap();
assert_eq!(v["counts"]["Circle"], 1, "{v}");
}
-1
View File
@@ -2,7 +2,6 @@ mod cli;
mod dash_limit_note; mod dash_limit_note;
mod drafting_spacing; mod drafting_spacing;
mod help; mod help;
mod lisp_script;
// DWG output needs craft-dwg's bridge. // DWG output needs craft-dwg's bridge.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_note; mod ltype_dwg_note;
+3 -4
View File
@@ -30,10 +30,6 @@ chrono = { workspace = true }
# Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`). # Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`).
# Already in Cargo.lock through eframe; same version so nothing is built twice. # Already in Cargo.lock through eframe; same version so nothing is built twice.
ron = "0.12" ron = "0.12"
# Waits for wgpu's answers while the graphics start (src/renderer.rs) and, on macOS, for the
# answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already in
# Cargo.lock through eframe.
pollster = "1"
[build-dependencies] [build-dependencies]
winresource = "0.1" winresource = "0.1"
@@ -60,6 +56,9 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
# The same winit eframe uses (the storytold fork, patched in the workspace). # The same winit eframe uses (the storytold fork, patched in the workspace).
# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs). # `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs).
winit = { version = "0.30", default-features = false, features = ["rwh_06"] } winit = { version = "0.30", default-features = false, features = ["rwh_06"] }
# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already
# in Cargo.lock through eframe.
pollster = "1"
# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a # Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a
# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C # kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C
# handler behind a safe API, without relaxing the workspace's unsafe-code lint. # handler behind a safe API, without relaxing the workspace's unsafe-code lint.
+3 -8
View File
@@ -23,10 +23,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
(CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"), (CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"),
(LOCALE, "the interface language, instead of the system's"), (LOCALE, "the interface language, instead of the system's"),
(VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"), (VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"),
( (STENCIL, "0 opens the window without a stencil buffer, for drivers that show a black window; clipped layout viewports then draw unclipped"),
STENCIL,
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
),
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"), (WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"), (NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"), (SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
@@ -49,10 +46,8 @@ pub(crate) struct Env {
pub(crate) locale: Option<String>, pub(crate) locale: Option<String>,
/// Present with vsync (default: off on Linux and BSD, on elsewhere). /// Present with vsync (default: off on Linux and BSD, on elsewhere).
pub(crate) vsync: Switch, pub(crate) vsync: Switch,
/// Off: the window has no stencil buffer; on: it keeps one on every attempt at starting the /// Off: the window has no stencil buffer (default: on). Some old drivers (Mesa on Intel HD
/// graphics. Default: it starts with one, and a start that can't draw with it drops it (see /// 4000, old Intel drivers on Windows) accept a stencil pass and then present a black window.
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
/// stencil pass and then present a black window.
pub(crate) stencil: Switch, pub(crate) stencil: Switch,
/// Keep the native Wayland backend instead of XWayland. /// Keep the native Wayland backend instead of XWayland.
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))] #[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
+36 -63
View File
@@ -33,7 +33,6 @@ mod nightly_session;
mod portable; mod portable;
mod process_identity; mod process_identity;
mod profile_root; mod profile_root;
mod renderer;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
mod sheet; mod sheet;
mod single_instance; mod single_instance;
@@ -240,38 +239,9 @@ fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> {
} }
} }
/// `Services::start_pick` for Linux and the BSDs: the blocking dialog runs on a thread of its
/// own, so the window keeps answering the desktop while the dialog is open; `ui` is woken when
/// it answers. If the thread cannot start, `done` is dropped unanswered and the app says the
/// dialog could not be shown.
#[cfg(all(unix, not(target_os = "macos")))]
fn start_pick(ui: egui::Context) -> cadcraft_ui_egui::StartPick {
Box::new(move |pick, done| {
let ui = ui.clone();
// Here, not on the thread: the interface language is this thread's
// (`i18n::with_language`), and the filter labels are translated.
let filters = filters(&pick);
let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || {
let dialog = file_dialog_with(&pick, &filters);
let picked = if matches!(pick, Pick::Save(_)) { dialog.save_file() } else { dialog.pick_file() };
done(picked.map(|p| p.to_string_lossy().to_string()));
ui.request_repaint();
});
if let Err(e) = spawned {
log::warn!("file dialog: {e}");
}
})
}
/// The blocking dialog for `pick` (Windows, Linux, FreeBSD). /// The blocking dialog for `pick` (Windows, Linux, FreeBSD).
fn file_dialog(pick: &Pick) -> rfd::FileDialog { fn file_dialog(pick: &Pick) -> rfd::FileDialog {
file_dialog_with(pick, &filters(pick)) let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
}
/// [`file_dialog`] offering `filters`, the file types of `pick` ([`filters`]) as the caller's
/// thread names them.
fn file_dialog_with(pick: &Pick, filters: &[(&'static str, Vec<&'static str>)]) -> rfd::FileDialog {
let dialog = filters.iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts));
match pick { match pick {
Pick::Save(name) => dialog.set_file_name(name), Pick::Save(name) => dialog.set_file_name(name),
Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir), Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir),
@@ -336,7 +306,7 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state /// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of /// saved by the last session is restored instead of opening centred. `stencil`: the stencil bits of
/// its render pass (each attempt at starting the graphics sets its own, see [`renderer::apply`]). /// its render pass ([`stencil_bits`]).
fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions { fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui::framework::Decision>) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default() let viewport = egui::ViewportBuilder::default()
.with_title(os_window::name_for(os_window::identity())) .with_title(os_window::name_for(os_window::identity()))
@@ -365,6 +335,17 @@ fn window_options(restoring: bool, stencil: u8, frame: Option<&cadcraft_ui_egui:
/// The key eframe saves the main window state under in its storage. /// The key eframe saves the main window state under in its storage.
const WINDOW_KEY: &str = "window"; const WINDOW_KEY: &str = "window";
/// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`).
const STENCIL_BITS: u8 = 8;
/// The stencil bits of the window's render pass: none when `CADCRAFT_STENCIL` is off. Some old
/// drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a stencil pass without an
/// error and then present a black window, so only an explicit opt-out drops it. Without a stencil
/// buffer, clipped layout viewports draw unclipped.
fn stencil_bits(stencil: Switch) -> u8 {
if stencil == Switch::Off { 0 } else { STENCIL_BITS }
}
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png"); const APP_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-macos-512.png");
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
@@ -564,6 +545,12 @@ fn main() -> eframe::Result {
cadcraft_engine::fonts::ttf::set_fallback_fonts(list); cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
} }
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos")))); let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
// The window's render pass and the canvas's pipelines must agree on it; a mismatch is a wgpu
// validation error.
let stencil = stencil_bits(vars.stencil);
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend. // XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On; let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11); let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
@@ -576,7 +563,7 @@ fn main() -> eframe::Result {
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync). // swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface), wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: persistence_path.clone(), persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), renderer::STENCIL_BITS, frame.as_ref()) ..window_options(restores_window(persistence_path.as_deref()), stencil, frame.as_ref())
}; };
if let Some(icon) = app_icon() { if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon); options.viewport = options.viewport.with_icon(icon);
@@ -613,13 +600,10 @@ fn main() -> eframe::Result {
let apple_events = &apple_events; let apple_events = &apple_events;
// The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it. // The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it.
let exit_watch = std::sync::Arc::clone(&nightly_watch); let exit_watch = std::sync::Arc::clone(&nightly_watch);
// Each attempt at starting the graphics sets its backends, adapter and stencil buffer, and a let result = eframe::run_native(
// failed one is followed by the next (see renderer.rs).
let result = renderer::run_native(
os_window::name_for(os_window::identity()), os_window::name_for(os_window::identity()),
options, options,
vars.stencil, Box::new(move |cc| {
Box::new(move |cc, started| {
cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?; cadcraft_ui_egui::framework::install(&cc.egui_ctx, forced_x11, frame.clone())?;
let mut app = CadApp::new(Session::empty(), services()); let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after // The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
@@ -634,13 +618,6 @@ fn main() -> eframe::Result {
if let Some(window) = cc.winit_window().cloned() { if let Some(window) = cc.winit_window().cloned() {
app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone())); app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone()));
} }
// On Linux and the BSDs the dialog is the desktop portal's, another process: waiting
// for it in the event handler leaves the window unanswered for as long as it is open,
// and the desktop then offers to force-quit the app.
#[cfg(all(unix, not(target_os = "macos")))]
{
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
}
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref()); let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
if let Some(ui) = restored { if let Some(ui) = restored {
app.ui = ui; app.ui = ui;
@@ -694,8 +671,9 @@ fn main() -> eframe::Result {
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync { if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240)); app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
} }
// On the GPU with the window's stencil buffer, or on the CPU when the GPU refuses the canvas. if let Some(rs) = &cc.wgpu_render_state {
started.install(&mut app, cc.wgpu_render_state.as_ref()); app.set_wgpu(rs, eframe::egui_wgpu::depth_format_from_bits(0, stencil));
}
if let Some(port) = control_port { if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone()); let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx); app = app.with_control(rx);
@@ -753,8 +731,10 @@ fn main() -> eframe::Result {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window}; use super::{
use crate::renderer::STENCIL_BITS; STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
without_tiny_window,
};
#[test] #[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() { fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -789,25 +769,18 @@ mod tests {
} }
/// `CADCRAFT_STENCIL=0` (also `no`, `false`, any case) opens the window without a stencil /// `CADCRAFT_STENCIL=0` (also `no`, `false`, any case) opens the window without a stencil
/// buffer, and `1` keeps it on every attempt; unset, blank or anything else starts with one and /// buffer; unset, blank, `1` or anything else keeps it.
/// lets a failed start drop it.
#[test] #[test]
fn the_stencil_buffer_follows_cadcraft_stencil() { fn the_stencil_buffer_is_dropped_only_when_asked() {
let stencils = |value: Option<&str>| { let bits = |value: Option<&str>| {
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(value).flatten().map(Into::into)); let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(value).flatten().map(Into::into));
let attempts = crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil); stencil_bits(vars.stencil)
attempts.iter().map(|a| a.stencil).collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>()
}; };
for off in ["0", "no", "NO", "false", "False", " 0 "] { for off in ["0", "no", "NO", "false", "False", " 0 "] {
assert_eq!(stencils(Some(off)), [false], "{off:?}"); assert_eq!(bits(Some(off)), 0, "{off:?}");
} }
for on in ["1", "yes", "On"] { for on in [None, Some(""), Some("1"), Some("yes"), Some("8"), Some("maybe")] {
assert_eq!(stencils(Some(on)), [true], "{on:?}"); assert_eq!(bits(on), STENCIL_BITS, "{on:?}");
}
for unset in [None, Some(""), Some("8"), Some("maybe")] {
assert_eq!(stencils(unset), [false, true], "{unset:?}");
let vars = crate::env::Env::from_vars(|k| (k == "CADCRAFT_STENCIL").then_some(unset).flatten().map(Into::into));
assert!(crate::renderer::attempts(eframe::wgpu::Backends::DX12, false, vars.stencil)[0].stencil, "{unset:?}: the first has one");
} }
} }
-660
View File
@@ -1,660 +0,0 @@
//! Which renderer draws the window, and what the app does when one can't start.
//!
//! The window draws with wgpu (eframe is built with its `wgpu` renderer only). Where a start fails
//! decides what is tried next:
//!
//! - The adapter, the device or the window's surface can't be made (no adapter for the backends, a
//! device the driver refuses or loses): eframe returns `Error::Wgpu` before the app exists. The
//! stencil buffer plays no part, so another adapter is tried.
//! - The window's surface can't be configured, or egui's pipelines are refused: also before the app
//! exists. The stencil buffer is part of both, so the same adapter is tried without it first.
//! - The driver takes the stencil buffer and then draws nothing, with no error: Mesa's OpenGL on Ivy
//! Bridge refuses `glTexStorage2D(GL_STENCIL_INDEX8)`, the frame buffer is incomplete and every
//! frame comes out black (#1724). egui makes the window's stencil buffer a texture it can also
//! sample, which wgpu's OpenGL backend stores with that call. Before the app is created, [`check`]
//! clears a small target, without and then with a stencil buffer made the same way, and reads it
//! back.
//! - The canvas's own pipelines are refused: the canvas draws on the CPU ([`Started::install`]).
//!
//! Not caught: a driver that crashes the process or hangs, a black window whose offscreen check
//! passes (a fault in presenting to the window), a failure after the app was created (an error
//! then ends the start as before), and a panic inside eframe or egui-wgpu.
//!
//! The attempts, in order ([`attempts`]): the start as it always was (DirectX 12 alone on Windows,
//! see `graphics.rs`; eframe's backends elsewhere); OpenGL alone, where those backends have it
//! beside another; then those backends with a software adapter only (WARP, llvmpipe). Each is tried
//! with a stencil buffer, then without. No attempt creates a backend the first one did not, so no
//! driver code runs that the start did not run before: on Windows, where OpenGL is left out because
//! an AMD driver crashes inside it (#31), the fallback is WARP. A start that works today makes only
//! the first attempt, and the check.
//!
//! `WGPU_BACKEND` limits every attempt to its backends, and `CADCRAFT_STENCIL` fixes the stencil
//! buffer. Nothing is remembered between starts: a failed attempt costs a fraction of a second, and
//! a remembered choice would keep a lesser renderer after a failure that happened once.
use std::sync::Arc;
use std::time::Duration;
use cadcraft_ui_egui::CadApp;
use cadcraft_ui_egui::switch::Switch;
use eframe::egui_wgpu::{self, NativeAdapterSelectorMethod, WgpuError, WgpuSetup};
use eframe::wgpu::{self, Backends, DeviceType};
/// Stencil bits of the window's render pass when an attempt has a stencil buffer (see
/// `NativeOptions::stencil_buffer`).
pub(crate) const STENCIL_BITS: u8 = 8;
/// How long [`check`] waits for its read-back. A slower answer counts as a pass: a busy GPU is no
/// reason to fall back.
const CHECK_TIMEOUT: Duration = Duration::from_secs(10);
/// The width of [`check`]'s target: one row of RGBA8 pixels is then exactly the row alignment a
/// copy to a buffer needs.
const CHECK_WIDTH: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT / 4;
/// The colour [`check`] clears to, as it reads back: a new texture starts as zeros.
const CHECK_COLOR: [u8; 4] = [255, 0, 255, 255];
type DynError = Box<dyn std::error::Error + Send + Sync>;
/// Builds the app once an attempt's window draws.
pub(crate) type Creator<'a> = Box<dyn FnOnce(&eframe::CreationContext<'_>, &Started) -> Result<Box<dyn eframe::App + 'a>, DynError> + 'a>;
/// The backends by name, for the log and the status bar.
const NAMES: [(Backends, &str); 4] =
[(Backends::DX12, "DirectX 12"), (Backends::METAL, "Metal"), (Backends::VULKAN, "Vulkan"), (Backends::GL, "OpenGL")];
/// One way to start the window's graphics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Attempt {
/// The backends wgpu chooses an adapter from.
pub(crate) backends: Backends,
/// Only a software adapter (WARP, llvmpipe); otherwise wgpu's choice, which prefers a GPU.
pub(crate) software: bool,
/// The window has a stencil buffer, which clips the contents of clipped layout viewports.
pub(crate) stencil: bool,
}
impl Attempt {
/// The same adapter: an attempt that differs only in its stencil buffer.
fn same_adapter(self, other: Attempt) -> bool {
(self.backends, self.software) == (other.backends, other.software)
}
}
impl std::fmt::Display for Attempt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let backends: Vec<&str> = NAMES.iter().filter(|n| self.backends.contains(n.0)).map(|n| n.1).collect();
f.write_str(&if backends.is_empty() { format!("{:?}", self.backends) } else { backends.join(" or ") })?;
if self.software {
f.write_str(" on a software adapter")?;
}
f.write_str(if self.stencil { "" } else { " without a stencil buffer" })
}
}
/// The attempts in order (see the module docs). `first`: the backends the start is configured with;
/// `requested`: they are `WGPU_BACKEND`'s, which every attempt keeps; `stencil`: `CADCRAFT_STENCIL`.
pub(crate) fn attempts(first: Backends, requested: bool, stencil: Switch) -> Vec<Attempt> {
let mut adapters = vec![(first, false)];
if !requested && first.contains(Backends::GL) && first != Backends::GL {
adapters.push((Backends::GL, false));
}
adapters.push((first, true));
let stencils: &[bool] = match stencil {
Switch::On => &[true],
Switch::Off => &[false],
Switch::Default => &[true, false],
};
adapters.into_iter().flat_map(|(backends, software)| stencils.iter().map(move |&stencil| Attempt { backends, software, stencil })).collect()
}
/// What a failed attempt says about the attempts after it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Failure {
/// The adapter, the device or the surface couldn't be made, or nothing was drawn: the same
/// adapter without a stencil buffer fails the same way.
Adapter,
/// Something the stencil buffer is part of failed: the same adapter without one may work.
Stencil,
}
/// The attempt to try after the one at `at` failed with `failure`: the next one after a stencil
/// failure, else the next on another adapter.
pub(crate) fn next(attempts: &[Attempt], at: usize, failure: Failure) -> Option<usize> {
let failed = *attempts.get(at)?;
attempts.iter().enumerate().skip(at + 1).find(|(_, a)| failure == Failure::Stencil || !a.same_adapter(failed)).map(|(i, _)| i)
}
/// What `error` from `eframe::run_native` says about the attempt: `None` when it isn't the graphics
/// (the app's own start, the windowing system).
pub(crate) fn classify(error: &eframe::Error) -> Option<Failure> {
match error {
eframe::Error::Wgpu(WgpuError::ConfigureSurface(_) | WgpuError::CreateRenderer(_)) => Some(Failure::Stencil),
eframe::Error::Wgpu(_) => Some(Failure::Adapter),
eframe::Error::AppCreation(error) => error.downcast_ref::<CheckFailed>().map(|c| c.failure),
_ => None,
}
}
/// The attempt to try after the one at `at` ended with `error`: none once the app was `created`,
/// since a failure after that is no start failure (and the app can't be built twice), and none for
/// an error that isn't the graphics'.
pub(crate) fn retry(attempts: &[Attempt], at: usize, created: bool, error: &eframe::Error) -> Option<usize> {
if created {
return None;
}
next(attempts, at, classify(error)?)
}
/// [`check`] found that the window can't draw. Returned from the app creator, it ends the attempt
/// before the app exists.
#[derive(Debug)]
pub(crate) struct CheckFailed {
failure: Failure,
message: String,
}
impl std::fmt::Display for CheckFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for CheckFailed {}
/// Clear a small target and read it back: as it is, then with a stencil buffer of `stencil`, made
/// as egui makes the window's (see the module docs). A target that doesn't come back cleared is a
/// [`Failure::Adapter`] without the stencil buffer and a [`Failure::Stencil`] with it.
pub(crate) fn check(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
passes(stencil, |format| clear_and_read(device, queue, format))
}
/// [`check`]'s passes, each made by `pass` with or without the stencil buffer: what failed names
/// the [`Failure`], and a device that didn't answer the first pass isn't waited for a second time.
fn passes(
stencil: Option<wgpu::TextureFormat>,
mut pass: impl FnMut(Option<wgpu::TextureFormat>) -> Result<bool, String>,
) -> Result<(), CheckFailed> {
let failed = |failure: Failure| move |message: String| CheckFailed { failure, message };
let answered = pass(None).map_err(failed(Failure::Adapter))?;
match stencil {
Some(format) if answered => pass(Some(format)).map(|_| ()).map_err(failed(Failure::Stencil)),
_ => Ok(()),
}
}
/// One pass of [`check`]: `Err` names what came back instead of [`CHECK_COLOR`]; `Ok(false)`: no
/// answer came, which counts as a pass.
fn clear_and_read(device: &wgpu::Device, queue: &wgpu::Queue, stencil: Option<wgpu::TextureFormat>) -> Result<bool, String> {
let size = wgpu::Extent3d { width: CHECK_WIDTH, height: 1, depth_or_array_layers: 1 };
let row = CHECK_WIDTH * 4;
let submitted = pollster::block_on(egui_wgpu::winit::catch_errors(device, || {
let texture = |format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("startup check"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let color = texture(wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
// The usage egui gives the window's depth and stencil texture.
let depth = stencil.map(|format| texture(format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING));
let color_view = color.create_view(&wgpu::TextureViewDescriptor::default());
let depth_view = depth.as_ref().map(|t| t.create_view(&wgpu::TextureViewDescriptor::default()));
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("startup check"),
size: u64::from(row),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let [r, g, b, a] = CHECK_COLOR.map(|c| f64::from(c) / 255.0);
drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("startup check"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &color_view,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }), store: wgpu::StoreOp::Store },
depth_slice: None,
})],
depth_stencil_attachment: depth_view.as_ref().zip(stencil).map(|(view, format)| wgpu::RenderPassDepthStencilAttachment {
view,
depth_ops: format.has_depth_aspect().then_some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
}),
..Default::default()
}));
encoder.copy_texture_to_buffer(
color.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None },
},
size,
);
queue.submit([encoder.finish()]);
buffer
}));
let buffer = submitted.map_err(|e| format!("the device refused the check: {e}"))?;
let (send, mapped) = std::sync::mpsc::channel();
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
let _ = send.send(result);
});
match device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(CHECK_TIMEOUT) }) {
Ok(_) => {}
Err(wgpu::PollError::Timeout) => {
log::warn!("graphics: the start-up check had no answer after {CHECK_TIMEOUT:?}; taken as passed");
return Ok(false);
}
Err(e) => return Err(format!("waiting for the check failed: {e}")),
}
match mapped.try_recv() {
Ok(Ok(())) => {}
Ok(Err(e)) => return Err(format!("the check could not be read back: {e}")),
Err(_) => {
log::warn!("graphics: the start-up check was not read back; taken as passed");
return Ok(false);
}
}
let pixels = buffer.slice(..).get_mapped_range().map_err(|e| format!("the check could not be read back: {e}"))?;
read_back(&pixels).map(|()| true)
}
/// Whether the row [`check`] read back is [`CHECK_COLOR`] throughout, within what a driver's
/// rounding could change.
fn read_back(pixels: &[u8]) -> Result<(), String> {
let row = CHECK_WIDTH as usize * CHECK_COLOR.len();
let cleared = |p: &[u8; CHECK_COLOR.len()]| p.iter().zip(CHECK_COLOR).all(|(&p, c)| p.abs_diff(c) <= 8);
match pixels.as_chunks::<{ CHECK_COLOR.len() }>().0.iter().find(|&p| !cleared(p)) {
Some(p) => Err(format!("a cleared target read back {p:?}, not {CHECK_COLOR:?}")),
None if pixels.len() == row => Ok(()),
None => Err(format!("the check read back {} bytes, not {row}", pixels.len())),
}
}
/// `options` for `attempt`: its backends, its adapter and its stencil buffer.
pub(crate) fn apply(options: &mut eframe::NativeOptions, attempt: Attempt) {
options.stencil_buffer = if attempt.stencil { STENCIL_BITS } else { 0 };
if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.instance_descriptor.backends = attempt.backends;
create.native_adapter_selector = attempt.software.then(|| Arc::new(software_adapter) as NativeAdapterSelectorMethod);
}
}
/// A software adapter of `adapters` that can show `surface`.
fn software_adapter(adapters: &[wgpu::Adapter], surface: Option<&wgpu::Surface<'_>>) -> Result<wgpu::Adapter, String> {
adapters
.iter()
.find(|a| a.get_info().device_type == DeviceType::Cpu && surface.is_none_or(|s| a.is_surface_supported(s)))
.cloned()
.ok_or_else(|| "no software adapter can show the window".to_owned())
}
/// Run eframe with each attempt in turn until one starts the window, then build the app with
/// `create`. `options` are as configured (their backends are `WGPU_BACKEND`'s or the platform's),
/// `stencil` is `CADCRAFT_STENCIL`. A failed attempt is dropped with its window before any app
/// exists; an error once the app was created ends the start, as before. When every attempt failed,
/// the first one's error is returned: it is the one the start as it always was would have given.
pub(crate) fn run_native(name: &str, options: eframe::NativeOptions, stencil: Switch, create: Creator<'_>) -> eframe::Result {
let requested = Backends::from_env().is_some();
let configured = match &options.wgpu_options.wgpu_setup {
WgpuSetup::CreateNew(create) => create.instance_descriptor.backends,
WgpuSetup::Existing(_) => Backends::all(),
};
// Only what this build has, so no attempt asks for a backend that can't be there.
let first = if requested { configured } else { configured & wgpu::Instance::enabled_backend_features() };
let attempts = attempts(first, requested, stencil);
// Later attempts reuse eframe's event loop, so the hooks a clone drops aren't needed again.
let template = options.clone();
let mut options = Some(options);
let mut create = Some(create);
let mut first_failure = None;
let mut why = None;
let mut at = 0;
while let Some(&attempt) = attempts.get(at) {
let mut attempt_options = options.take().unwrap_or_else(|| template.clone());
apply(&mut attempt_options, attempt);
fault::refuse_adapter(&mut attempt_options, at);
log::info!("graphics: starting with {attempt} (attempt {} of {})", at + 1, attempts.len());
let started = Started { attempt, index: at, why: why.clone() };
let slot = &mut create;
let result = eframe::run_native(
name,
attempt_options,
Box::new(|cc| {
if let Some(rs) = &cc.wgpu_render_state {
fault::check(started.index, started.stencil_format())?;
let checking = std::time::Instant::now();
check(&rs.device, &rs.queue, started.stencil_format())?;
log::info!("graphics: the start-up check passed in {:.1?}", checking.elapsed());
}
let create = slot.take().ok_or("the app was already created")?;
create(cc, &started)
}),
);
let Err(error) = result else { return Ok(()) };
let Some(after) = retry(&attempts, at, create.is_none(), &error) else {
if create.is_none() || classify(&error).is_none() {
return Err(error);
}
log::error!("graphics: {attempt} failed: {error}; no other renderer is left to try");
return Err(first_failure.unwrap_or(error));
};
log::warn!("graphics: {attempt} failed: {error}; trying the next renderer");
// The first failure says why the first choice isn't drawing; the log has the others.
why.get_or_insert_with(|| format!("{attempt} failed: {}", error.to_string().lines().next().unwrap_or_default()));
first_failure.get_or_insert(error);
at = after;
}
Err(first_failure.unwrap_or_else(|| eframe::Error::AppCreation("no renderer to start the window with".into())))
}
/// The attempt that started the window, handed to the app creator.
pub(crate) struct Started {
attempt: Attempt,
/// Its position in [`attempts`].
index: usize,
/// Why the first attempt isn't the one drawing.
why: Option<String>,
}
impl Started {
/// The format of the window's stencil buffer, which the canvas's pipelines must match.
fn stencil_format(&self) -> Option<wgpu::TextureFormat> {
egui_wgpu::depth_format_from_bits(0, if self.attempt.stencil { STENCIL_BITS } else { 0 })
}
/// Draw the canvas on the GPU with the window's render state `rs`, or on the CPU when its
/// pipelines are refused. Logs which renderer draws, and says in the status bar why when it is
/// not the first choice (unless the start already put something there).
pub(crate) fn install(&self, app: &mut CadApp, rs: Option<&egui_wgpu::RenderState>) {
let Some(rs) = rs else { return };
let stencil = self.stencil_format();
let installed = pollster::block_on(egui_wgpu::winit::catch_errors(&rs.device, || app.set_wgpu(rs, stencil)));
let canvas_failed = match installed {
Err(e) => Some(e.to_string()),
Ok(()) => fault::canvas(self.index),
};
if canvas_failed.is_some() {
app.canvas.gpu = None;
app.canvas.gpu_device = None;
}
let info = rs.adapter.get_info();
log::info!(
"graphics: {} draws the window on {} ({:?}, {:?}, driver {}); the canvas draws on the {}",
self.attempt,
info.name.trim(),
info.backend,
info.device_type,
[info.driver.trim(), info.driver_info.trim()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" "),
if canvas_failed.is_some() { "CPU" } else { "GPU" }
);
if !self.attempt.stencil {
log::warn!("graphics: no stencil buffer: clipped layout viewports draw unclipped");
}
let note = match (&self.why, &canvas_failed) {
(_, Some(error)) => {
Some(cadcraft_ui_egui::tf!("Graphics: the drawing area draws on the CPU, because the GPU refused it: {error}", error = error))
}
(Some(why), None) => Some(cadcraft_ui_egui::tf!("Graphics: drawing with {renderer}, because {why}", renderer = self.attempt, why = why)),
(None, None) => None,
};
if let Some(note) = note {
log::warn!("{note}");
if app.status.is_none() {
app.set_status(note);
}
}
}
}
/// A test switch read only by debug builds: `CADCRAFT_GRAPHICS_FAULT=<attempt>:<step>[,...]` fails
/// the attempt at that position in [`attempts`] (from 0) at `adapter` (its adapter is refused),
/// `draw` or `stencil` ([`check`]'s pass without or with the stencil buffer), or `canvas` (the
/// canvas's pipelines), so each fallback can be run on a machine whose graphics work.
mod fault {
use super::{Arc, CheckFailed, Failure, NativeAdapterSelectorMethod, WgpuSetup, wgpu};
#[cfg(debug_assertions)]
fn asked(index: usize, step: &str) -> bool {
listed(std::env::var("CADCRAFT_GRAPHICS_FAULT").ok().as_deref(), index, step)
}
#[cfg(not(debug_assertions))]
fn asked(_index: usize, _step: &str) -> bool {
false
}
/// Whether `value` lists `<index>:<step>`.
#[cfg(any(debug_assertions, test))]
pub(super) fn listed(value: Option<&str>, index: usize, step: &str) -> bool {
value.is_some_and(|v| v.split(',').any(|f| f.trim().split_once(':') == Some((index.to_string().as_str(), step))))
}
pub(super) fn refuse_adapter(options: &mut eframe::NativeOptions, index: usize) {
if asked(index, "adapter")
&& let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
let refuse = |_: &[wgpu::Adapter], _: Option<&wgpu::Surface<'_>>| Err("refused by CADCRAFT_GRAPHICS_FAULT".to_owned());
create.native_adapter_selector = Some(Arc::new(refuse) as NativeAdapterSelectorMethod);
}
}
pub(super) fn check(index: usize, stencil: Option<wgpu::TextureFormat>) -> Result<(), CheckFailed> {
let fail = |failure, step| CheckFailed { failure, message: format!("the {step} check failed (CADCRAFT_GRAPHICS_FAULT)") };
if asked(index, "draw") {
return Err(fail(Failure::Adapter, "draw"));
}
if stencil.is_some() && asked(index, "stencil") {
return Err(fail(Failure::Stencil, "stencil"));
}
Ok(())
}
pub(super) fn canvas(index: usize) -> Option<String> {
asked(index, "canvas").then(|| "refused by CADCRAFT_GRAPHICS_FAULT".to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
const ANY: Backends = Backends::VULKAN.union(Backends::GL);
/// A short name of `attempt`, to read the order in the asserts.
fn key(attempt: &Attempt) -> String {
let short = [(Backends::DX12, "dx12"), (Backends::METAL, "metal"), (Backends::VULKAN, "vulkan"), (Backends::GL, "gl")];
let mut key = short.iter().filter(|(b, _)| attempt.backends.contains(*b)).map(|(_, n)| *n).collect::<Vec<_>>().join("+");
if attempt.software {
key.push_str(" software");
}
if !attempt.stencil {
key.push_str(" no-stencil");
}
key
}
fn keys(list: &[Attempt]) -> Vec<String> {
list.iter().map(key).collect()
}
/// The first attempt is the start as it always was; OpenGL alone comes only where it was one of
/// several, then the same backends on a software adapter, each with and then without a stencil
/// buffer. `WGPU_BACKEND` keeps its backends on every attempt, and `CADCRAFT_STENCIL` its choice.
#[test]
fn the_attempts_begin_with_the_start_as_it_was_and_keep_explicit_choices() {
let linux = attempts(ANY, false, Switch::Default);
assert_eq!(keys(&linux), ["vulkan+gl", "vulkan+gl no-stencil", "gl", "gl no-stencil", "vulkan+gl software", "vulkan+gl software no-stencil"]);
// Windows: DirectX 12 alone (graphics.rs), so the fallback never creates OpenGL there.
let windows = attempts(Backends::DX12, false, Switch::Default);
assert_eq!(keys(&windows), ["dx12", "dx12 no-stencil", "dx12 software", "dx12 software no-stencil"]);
// WGPU_BACKEND=vulkan,gl: no attempt leaves its backends.
assert!(attempts(ANY, true, Switch::Default).iter().all(|a| a.backends == ANY));
assert_eq!(attempts(Backends::GL, false, Switch::Default).len(), 4, "OpenGL alone is already the first");
// CADCRAFT_STENCIL: off is never on, on is never dropped.
assert!(attempts(ANY, false, Switch::Off).iter().all(|a| !a.stencil));
assert!(attempts(ANY, false, Switch::On).iter().all(|a| a.stencil));
assert_eq!(attempts(ANY, false, Switch::On).len() * 2, linux.len());
}
/// A stencil failure tries the same adapter without the stencil buffer; any other failure skips
/// that twin and tries the next adapter; past the last there is nothing.
#[test]
fn a_failure_picks_the_next_attempt_by_what_failed() {
let list = attempts(ANY, false, Switch::Default);
let at = |k: &str| list.iter().position(|a| key(a) == k).unwrap();
let next_key = |from: &str, failure| next(&list, at(from), failure).map(|i| key(&list[i]));
assert_eq!(next_key("vulkan+gl", Failure::Stencil).as_deref(), Some("vulkan+gl no-stencil"));
assert_eq!(next_key("vulkan+gl", Failure::Adapter).as_deref(), Some("gl"));
assert_eq!(next_key("vulkan+gl no-stencil", Failure::Adapter).as_deref(), Some("gl"));
assert_eq!(next_key("gl no-stencil", Failure::Stencil).as_deref(), Some("vulkan+gl software"));
assert_eq!(next_key("vulkan+gl software", Failure::Adapter), None);
assert_eq!(next_key("vulkan+gl software no-stencil", Failure::Stencil), None);
assert_eq!(next(&list, list.len(), Failure::Stencil), None);
// CADCRAFT_STENCIL=1: a stencil failure has no twin to fall back to, so the next adapter.
let on = attempts(Backends::DX12, false, Switch::On);
assert_eq!(next(&on, 0, Failure::Stencil), Some(1));
assert!(on[1].software);
}
/// Errors before the app exists are graphics failures; which kind decides the next attempt. The
/// app's own errors and the windowing system's are not, so they end the start as before.
#[test]
fn start_errors_are_sorted_by_what_failed() {
let no_adapter = eframe::Error::Wgpu(WgpuError::CustomNativeAdapterSelectionError("none".into()));
assert_eq!(classify(&no_adapter), Some(Failure::Adapter));
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable)), Some(Failure::Adapter));
let refused = || wgpu::Error::Validation { source: Box::new(std::fmt::Error), description: "refused".into() };
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::ConfigureSurface(refused()))), Some(Failure::Stencil));
assert_eq!(classify(&eframe::Error::Wgpu(WgpuError::CreateRenderer(refused()))), Some(Failure::Stencil));
for failure in [Failure::Adapter, Failure::Stencil] {
let failed = eframe::Error::AppCreation(Box::new(CheckFailed { failure, message: "black".into() }));
assert_eq!(classify(&failed), Some(failure));
}
assert_eq!(classify(&eframe::Error::AppCreation("the app's own start".into())), None);
}
/// Only a graphics failure before the app exists is retried: once the app was created an error
/// ends the start (the app can't be built twice), as does an error that isn't the graphics'.
#[test]
fn only_a_start_failure_before_the_app_exists_is_retried() {
let list = attempts(Backends::DX12, false, Switch::Default);
let gpu = eframe::Error::Wgpu(WgpuError::NoSurfaceFormatsAvailable);
assert_eq!(retry(&list, 0, false, &gpu), Some(2));
assert_eq!(retry(&list, 0, true, &gpu), None);
let black = eframe::Error::AppCreation(Box::new(CheckFailed { failure: Failure::Stencil, message: "black".into() }));
assert_eq!(retry(&list, 0, false, &black), Some(1));
assert_eq!(retry(&list, 0, false, &eframe::Error::AppCreation("the app's own start".into())), None);
}
/// Each attempt takes its backends, its adapter and its stencil buffer.
#[test]
fn an_attempt_sets_its_backends_adapter_and_stencil_buffer() {
let mut options = eframe::NativeOptions::default();
for attempt in attempts(Backends::VULKAN | Backends::GL, false, Switch::Default) {
apply(&mut options, attempt);
let WgpuSetup::CreateNew(create) = &options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
assert_eq!(create.instance_descriptor.backends, attempt.backends);
assert_eq!(create.native_adapter_selector.is_some(), attempt.software, "{attempt}");
assert_eq!(options.stencil_buffer > 0, attempt.stencil, "{attempt}");
}
}
/// The read-back is answered and passes on a working device, with and without a stencil
/// buffer. The device is made as the app makes it: on Windows DirectX 12 alone with FXC
/// (graphics.rs; an AMD driver crashes when OpenGL is created there, #31), and egui's limits for
/// the adapter.
#[test]
fn the_check_passes_on_a_device_that_draws() {
let mut options = eframe::NativeOptions::default();
crate::graphics::configure(&mut options, if cfg!(windows) { None } else { Some(Backends::all()) }, None);
let WgpuSetup::CreateNew(mut create) = options.wgpu_options.wgpu_setup else { panic!("eframe creates its own wgpu setup") };
create.instance_descriptor.backends.remove(Backends::BROWSER_WEBGPU);
let setup = WgpuSetup::CreateNew(create);
let instance = pollster::block_on(setup.new_instance());
let config = egui_wgpu::WgpuConfiguration { wgpu_setup: setup, ..Default::default() };
let Ok(rs) = pollster::block_on(egui_wgpu::RenderState::create(&config, &instance, None, Default::default())) else {
eprintln!("no graphics adapter here: the device check is left to machines with one");
return;
};
let info = rs.adapter.get_info();
for stencil in [None, Some(wgpu::TextureFormat::Stencil8)] {
// `check` takes no answer as a pass; a working device must answer, or every start on it
// would wait for the timeout.
let started = std::time::Instant::now();
let read = clear_and_read(&rs.device, &rs.queue, stencil);
let elapsed = started.elapsed();
assert_eq!(read, Ok(true), "{stencil:?} on {} ({:?}, {:?}) after {elapsed:?}", info.name, info.backend, info.device_type);
}
}
/// The read-back passes only when every pixel came back cleared: a target the clear never
/// reached still holds the zeros a texture starts as.
#[test]
fn the_check_fails_a_target_the_clear_did_not_reach() {
let row = |pixel: [u8; 4]| pixel.repeat(CHECK_WIDTH as usize);
assert!(read_back(&row(CHECK_COLOR)).is_ok());
assert!(read_back(&row([250, 6, 251, 255])).is_ok(), "a driver's rounding");
assert!(read_back(&row([0, 0, 0, 0])).is_err(), "never cleared");
assert!(read_back(&row([255, 0, 255, 0])).is_err(), "another alpha");
let mut one_off = row(CHECK_COLOR);
one_off[CHECK_COLOR.len() * 7 + 1] = 200;
assert!(read_back(&one_off).is_err(), "one pixel the clear missed");
assert!(read_back(&row(CHECK_COLOR)[..8]).is_err(), "a short read");
assert!(read_back(&[]).is_err());
}
/// A target that didn't come back cleared blames the adapter without the stencil buffer and the
/// stencil buffer with it; no answer is a pass, and isn't waited for twice.
#[test]
fn a_failed_pass_names_what_failed() {
let stencil = Some(wgpu::TextureFormat::Stencil8);
let failure = |black_with: Option<bool>| {
passes(stencil, |format| if black_with.is_none_or(|with| with == format.is_some()) { Err("black".into()) } else { Ok(true) })
.map_err(|e| e.failure)
};
assert_eq!(failure(Some(false)), Err(Failure::Adapter), "black without the stencil buffer");
assert_eq!(failure(None), Err(Failure::Adapter), "black either way");
assert_eq!(failure(Some(true)), Err(Failure::Stencil), "black only with it");
let mut asked = Vec::new();
let unanswered = passes(stencil, |format| {
asked.push(format);
Ok(false)
});
assert!(unanswered.is_ok());
assert_eq!(asked, [None], "no second wait after no answer");
let mut asked = Vec::new();
let answered = passes(stencil, |format| {
asked.push(format);
Ok(true)
});
assert!(answered.is_ok());
assert_eq!(asked, [None, stencil], "both passes when the first answered");
}
/// The test switch names attempts by position and step, and nothing else trips it.
#[test]
fn the_fault_switch_names_one_step_of_one_attempt() {
assert!(fault::listed(Some("0:stencil"), 0, "stencil"));
assert!(fault::listed(Some(" 2:adapter , 0:draw"), 0, "draw"));
assert!(!fault::listed(Some("0:stencil"), 1, "stencil"));
assert!(!fault::listed(Some("10:draw"), 1, "draw"));
assert!(!fault::listed(Some("0:stencils"), 0, "stencil"));
assert!(!fault::listed(None, 0, "draw"));
}
/// The log and the status bar tell the attempts apart.
#[test]
fn an_attempt_names_what_it_tries() {
let list = attempts(ANY, false, Switch::Default);
let names: std::collections::BTreeSet<String> = list.iter().map(ToString::to_string).collect();
assert_eq!(names.len(), list.len());
}
}
+20 -23
View File
@@ -206,7 +206,8 @@ pub fn next_id(d: &Drawing) -> u32 {
/// Interpret a constraint against the model's current parameters, appending its auxiliary /// Interpret a constraint against the model's current parameters, appending its auxiliary
/// unknowns (contact parameters) to the model, settled with the geometry held still. /// unknowns (contact parameters) to the model, settled with the geometry held still.
pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> { pub(crate) fn interpret(c: &Constraint, model: &mut Model, target: f64) -> Result<Built, String> {
let mut b = Built::new(c, model, &model.x0, target)?; let x = model.x0.clone();
let mut b = Built::new(c, model, &x, target)?;
if b.aux_init.is_empty() { if b.aux_init.is_empty() {
return Ok(b); return Ok(b);
} }
@@ -526,26 +527,22 @@ pub fn solve(d: &mut Drawing, opts: &SolveOptions) -> Result<SolveReport, SolveE
/// Largest residual of each constraint at the current geometry (`None` when it cannot be /// Largest residual of each constraint at the current geometry (`None` when it cannot be
/// interpreted). /// interpreted).
pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> { pub fn residuals(d: &Drawing) -> Vec<(u32, Option<f64>)> {
residuals_with_model(d, residual_model(d)).collect()
}
fn residual_model(d: &Drawing) -> Model {
let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
Model::build(d, &handles)
}
fn residuals_with_model(d: &Drawing, mut model: Model) -> impl Iterator<Item = (u32, Option<f64>)> + '_ {
let mut e = env(d); let mut e = env(d);
let mut out = Vec::new(); let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
d.constraints.iter().take(MAX_CONSTRAINTS).map(move |c| { let mut model = Model::build(d, &handles);
let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) }; d.constraints
let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| { .iter()
out.clear(); .take(MAX_CONSTRAINTS)
b.eval(&model, &model.x0, &mut out); .map(|c| {
lm::max_abs(&out) let target = if c.kind.is_dimensional() { constraint_value(&mut e, c).ok() } else { Some(0.0) };
}); let r = target.and_then(|t| interpret(c, &mut model, t).ok()).map(|b| {
(c.id, r) let mut out = Vec::new();
}) b.eval(&model, &model.x0, &mut out);
lm::max_abs(&out)
});
(c.id, r)
})
.collect()
} }
/// Put back what each Fix locks where `before` had it, and report whether anything moved. /// Put back what each Fix locks where `before` had it, and report whether anything moved.
@@ -686,9 +683,9 @@ pub fn moved_anchors(d: &Drawing, before: &Drawing) -> Vec<(u32, Vec2)> {
/// True when every interpretable constraint holds at the current geometry. /// True when every interpretable constraint holds at the current geometry.
pub fn all_satisfied(d: &Drawing) -> bool { pub fn all_satisfied(d: &Drawing) -> bool {
let model = residual_model(d); let handles: Vec<Handle> = d.constraints.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect();
let tol = scale_tol(&model.x0) * 10.0; let tol = scale_tol(&Model::build(d, &handles).x0) * 10.0;
residuals_with_model(d, model).all(|(_, r)| r.is_none_or(|v| v <= tol)) residuals(d).iter().all(|(_, r)| r.is_none_or(|v| v <= tol))
} }
/// Check that a constraint's references make sense for its type. /// Check that a constraint's references make sense for its type.
+16 -36
View File
@@ -222,27 +222,6 @@ pub(crate) fn null_space(m: &[f64], rows: usize, cols: usize) -> (usize, Vec<Vec
(rank, basis) (rank, basis)
} }
/// Weighted normal matrix J W⁻¹ Jᵀ. Most constraint rows depend on only a few free coordinates.
fn normal_matrix(jac: &[f64], inverse_weights: &[f64], rows: usize) -> Vec<f64> {
let mut matrix = vec![0.0; rows * rows];
let mut terms = Vec::new();
let width = inverse_weights.len();
for (i, row) in jac.chunks_exact(width).enumerate() {
terms.clear();
terms.extend(row.iter().enumerate().filter(|(_, value)| **value != 0.0).map(|(col, &value)| (col, value, inverse_weights[col])));
for (k, other) in jac.chunks_exact(width).enumerate().skip(i) {
let sum = if terms.len() == width {
row.iter().zip(other).zip(inverse_weights).fold(0.0, |sum, ((&v, &other_v), &weight)| sum + v * other_v * weight)
} else {
terms.iter().fold(0.0, |sum, &(col, v, weight)| sum + v * other[col] * weight)
};
matrix[i * rows + k] = sum;
matrix[k * rows + i] = sum;
}
}
matrix
}
/// Run the solver from `x0`. Only `free` parameters change. /// Run the solver from `x0`. Only `free` parameters change.
pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize], weights: &[f64], tol: f64, max_iter: usize) -> Outcome { pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize], weights: &[f64], tol: f64, max_iter: usize) -> Outcome {
let mut x = x0.to_vec(); let mut x = x0.to_vec();
@@ -264,7 +243,22 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
while iter < max_iter { while iter < max_iter {
iter += 1; iter += 1;
let jac = jacobian(f, &x, free, rows); let jac = jacobian(f, &x, free, rows);
let a = normal_matrix(&jac, &winv, rows); // A = J W⁻¹ Jᵀ
let mut a = vec![0.0; rows * rows];
for i in 0..rows {
for k in i..rows {
let mut s = 0.0;
for (c, w) in winv.iter().enumerate() {
s += jac.get(i * nf + c).copied().unwrap_or(0.0) * jac.get(k * nf + c).copied().unwrap_or(0.0) * w;
}
if let Some(v) = a.get_mut(i * rows + k) {
*v = s;
}
if let Some(v) = a.get_mut(k * rows + i) {
*v = s;
}
}
}
let diag_max = (0..rows).map(|i| a.get(i * rows + i).copied().unwrap_or(0.0)).fold(0.0f64, f64::max).max(1e-12); let diag_max = (0..rows).map(|i| a.get(i * rows + i).copied().unwrap_or(0.0)).fold(0.0f64, f64::max).max(1e-12);
let mut improved = false; let mut improved = false;
for _ in 0..12 { for _ in 0..12 {
@@ -316,20 +310,6 @@ pub(crate) fn solve(f: &dyn Fn(&[f64], &mut Vec<f64>), x0: &[f64], free: &[usize
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn sparse_and_dense_constraints_keep_their_weighted_cross_terms() {
// Includes an empty row, an unconstrained column in a sparse row, and a tiny derivative.
let rows = [[-0., 0., -0., -0.], [2., 0., -3., 0.], [0., 0., 0., 1e-12], [1., 3., 2., -5.]];
let weights = [1., 0.25, 0.5, 2.];
let matrix = normal_matrix(&rows.concat(), &weights, rows.len());
for (i, row) in rows.iter().enumerate() {
for (k, other) in rows.iter().enumerate() {
let reference = (0..weights.len()).fold(0.0, |sum, c| sum + row[c] * other[c] * weights[c]);
assert_eq!(matrix[i * rows.len() + k].to_bits(), reference.to_bits());
}
}
}
#[test] #[test]
fn dense_and_rank() { fn dense_and_rank() {
let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap(); let y = solve_dense(vec![2.0, 1.0, 1.0, 3.0], vec![3.0, 5.0], 2).unwrap();
+1 -2
View File
@@ -619,8 +619,7 @@ impl EntityKind {
EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(), EntityKind::Polyline3d(p) => p.points.iter().map(|q| q.xy()).collect(),
EntityKind::Spline(s) => { EntityKind::Spline(s) => {
if s.fit.is_empty() { if s.fit.is_empty() {
// One grip per control vertex: a closed spline's repeats have none (#3566). s.control.clone()
s.control.iter().take(s.distinct_controls()).copied().collect()
} else { } else {
s.fit.clone() s.fit.clone()
} }
+32 -431
View File
@@ -246,68 +246,23 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
/// the same way the renderer places it (the stroke font is about 0.88 of the height per character). /// the same way the renderer places it (the stroke font is about 0.88 of the height per character).
fn text_box(t: &crate::Text, len: usize) -> Bounds2 { fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
use crate::{HAlign, VAlign}; use crate::{HAlign, VAlign};
let natural = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64; let w = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64;
// Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11). // Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11).
let origin = t.justify_point(); let origin = t.justify_point();
// Aligned and Fit text span their two points (groups 10 and 11) whatever rotation is stored:
// the line runs from the first to the second, Fit at its own height with its width stretched,
// Aligned at the height that keeps its proportions. With no second point, or one on the
// first, they are placed like left-justified text, as the renderer places them.
let second = t.align_pt.map(|p| p.xy()).filter(|_| matches!(t.halign, HAlign::Aligned | HAlign::Fit));
let span = second.map(|p| origin.dist(p)).filter(|d| d.is_finite() && *d > 1e-12);
// The fonts shape with the width factor as it is, not floored like the fallback width above,
// with 1 when it is unusable, and with a height of 1 when the height is.
let usable = t.width_factor.is_finite() && t.width_factor.abs() > 1e-6;
let wf = if usable { t.width_factor.abs() } else { 1.0 };
let height = if t.height.is_finite() && t.height > 0.0 { t.height } else { 1.0 };
let shaped = height * 0.9 * wf * len.max(1) as f64;
// Fit text is stretched by scaling its width factor by span / shaped width and shaping again.
// When the scaled factor is one the fonts cannot use (the stored one is, or the span is a tiny
// part of the text's width), the text is not stretched: it is drawn at a factor of 1.
// The shaped width here is an estimate, and the fonts decide by their own: it is taken to be
// within this factor of the estimate. Where the fonts decide by a cutoff, the box is the larger
// of the two outcomes unless the estimate is clear of the cutoff by this factor.
const MARGIN: f64 = 4.0;
let fits = |d: f64| {
let fitted = wf * d / shaped;
usable && fitted.is_finite() && fitted > 1e-6 * MARGIN
};
let unstretched = height * 0.9 * len.max(1) as f64;
// The fonts leave a line of next to no width as it is, neither stretched nor scaled.
let no_width = shaped * MARGIN <= 1e-12;
let (w, h, rotation) = match (span, second) {
(Some(_), Some(p)) if no_width => (shaped, height, origin.angle_to(p)),
// Unstretched is the larger outcome: a span this near the cutoff is far shorter than the text.
(Some(d), Some(p)) if t.halign == HAlign::Fit && !fits(d) => (unstretched, height, origin.angle_to(p)),
(Some(d), Some(p)) if t.halign == HAlign::Fit => (d, height, origin.angle_to(p)),
// Shrunk into a span shorter than its width, Aligned text is no taller than its own height,
// however narrow its characters are.
(Some(d), Some(p)) => (d, (height * d / shaped).max(height), origin.angle_to(p)),
_ => (natural, t.height, t.rotation),
};
let dx = match t.halign { let dx = match t.halign {
HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0, HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0,
HAlign::Center | HAlign::Middle => -w / 2.0, HAlign::Center | HAlign::Middle => -w / 2.0,
HAlign::Right => -w, HAlign::Right => -w,
}; };
let dy = match (t.halign, t.valign) { let dy = match (t.halign, t.valign) {
(HAlign::Middle, _) => -h / 2.0, (HAlign::Middle, _) => -t.height / 2.0,
(_, VAlign::Baseline) => 0.0, (_, VAlign::Baseline) => 0.0,
(_, VAlign::Bottom) => h / 3.0, (_, VAlign::Bottom) => t.height / 3.0,
(_, VAlign::Middle) => -h / 2.0, (_, VAlign::Middle) => -t.height / 2.0,
(_, VAlign::Top) => -h, (_, VAlign::Top) => -t.height,
}; };
let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + h), Vec2::new(dx, dy + h)]; let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + t.height), Vec2::new(dx, dy + t.height)];
Bounds2::from_points(local.map(|p| origin + p.rotate(rotation))) Bounds2::from_points(local.map(|p| origin + p.rotate(t.rotation)))
}
/// Whether `e` is a point on the layer Defpoints (the name in any case), as the block of a
/// dimension holds the dimension's definition points. The reference app selects a dimension and a
/// block reference by such a point of its block whatever a viewport freezes, the layer Defpoints
/// too, where a line on that layer follows the viewport. So a selection through a viewport counts
/// such a part of a block ([`ViewportBounds`]); the viewport itself does not draw it.
pub fn point_on_defpoints(e: &Entity) -> bool {
matches!(e.kind, EntityKind::Point(_)) && e.common.layer.eq_ignore_ascii_case("Defpoints")
} }
/// Whether an entity inside a block definition shows: its own invisible flag and its layer count, /// Whether an entity inside a block definition shows: its own invisible flag and its layer count,
@@ -315,27 +270,16 @@ pub fn point_on_defpoints(e: &Entity) -> bool {
/// entities a visibility state hides are invisible this way, and they sit far from the block's /// entities a visibility state hides are invisible this way, and they sit far from the block's
/// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked. /// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked.
/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]). /// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]).
/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]); a fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool {
/// point on the layer Defpoints counts whatever that viewport freezes ([`point_on_defpoints`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool {
let frozen: &[String] = if point_on_defpoints(e) { &[] } else { frozen };
// Attribute definitions are not drawn in an insert (its attribs are, see below), except // Attribute definitions are not drawn in an insert (its attribs are, see below), except
// constant ones, which the insert's bounds add on their own. // constant ones, which the insert's bounds add on their own.
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen) !matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
} }
/// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which /// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which
/// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`. /// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`.
/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through, fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
/// which does not draw them (the names compared as the renderer compares them). layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts))
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool {
layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen_in(frozen, layer))
}
/// Whether `layer` is one of the layers in `frozen`, those frozen in a layout viewport (the names
/// compared as the renderer compares them).
fn frozen_in(frozen: &[String], layer: &str) -> bool {
frozen.iter().any(|f| f.eq_ignore_ascii_case(layer))
} }
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its /// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
@@ -369,18 +313,13 @@ impl Contents<'_> {
} }
} }
/// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`: the parts that /// [`Contents`] of `blk` referenced at `depth`, measured once and kept in `blocks`.
/// count there ([`in_block_visible`], and a constant value by its layer as [`layer_counts`] says),
/// so those on a layer in `frozen` are left out ([`bounds_in`] says what the maps hold and why the
/// depth is part of the key).
fn contents<'a, 'm>( fn contents<'a, 'm>(
d: &'a Drawing, d: &'a Drawing,
blk: &'a crate::Block, blk: &'a crate::Block,
depth: usize, depth: usize,
blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>, blocks: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool, off_counts: bool,
frozen: &[String],
) -> Option<&'m Contents<'a>> { ) -> Option<&'m Contents<'a>> {
let key = (blk.name.as_str(), depth); let key = (blk.name.as_str(), depth);
if !blocks.contains_key(&key) { if !blocks.contains_key(&key) {
@@ -395,13 +334,11 @@ fn contents<'a, 'm>(
&& attmode != 0 && attmode != 0
&& (!a.invisible || attmode == 2) && (!a.invisible || attmode == 2)
&& be.common.visible && be.common.visible
&& layer_counts(d, &be.common.layer, off_counts, frozen) => && layer_counts(d, &be.common.layer, off_counts) =>
{ {
c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation()))); c.constants.push((a.tag.as_str(), constant_box(a, be.common.matches_layout_orientation())));
} }
_ if in_block_visible(d, be, off_counts, frozen) => { _ if in_block_visible(d, be, off_counts) => c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, off_counts)),
c.geometry = c.geometry.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen));
}
_ => {} _ => {}
} }
} }
@@ -410,20 +347,6 @@ fn contents<'a, 'm>(
blocks.get(&key) blocks.get(&key)
} }
/// [`Contents`] of the block `blk`, referenced at `depth`, as the drawing shows them: no viewport's
/// frozen layers are left out. For a clipped reference measured through a viewport ([`bounds_in`]).
/// `in_drawing` keeps them, apart from that viewport's own block bounds.
fn drawing_contents<'a, 'm>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
off_counts: bool,
in_drawing: &'m mut HashMap<(&'a str, usize), Contents<'a>>,
) -> Option<&'m Contents<'a>> {
// With no layer left out, the measure never asks for the drawing's boxes itself.
contents(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[])
}
/// The box of a constant attribute definition's value, as a block reference draws it: upright /// The box of a constant attribute definition's value, as a block reference draws it: upright
/// when the definition matches the layout's orientation, like other text (#2498). /// when the definition matches the layout's orientation, like other text (#2498).
fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 { fn constant_box(a: &crate::Attrib, upright: bool) -> Bounds2 {
@@ -471,13 +394,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 {
/// The box of what `e` draws (block contents on layers turned off left out). /// The box of what `e` draws (block contents on layers turned off left out).
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new()) bounds_of(d, e, depth, false, &mut HashMap::new())
} }
/// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer /// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer
/// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not). /// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not).
pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 { pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new()) bounds_of(d, e, 0, true, &mut HashMap::new())
} }
/// The bounds of block contents measured so far, kept across the entities of one unchanged /// The bounds of block contents measured so far, kept across the entities of one unchanged
@@ -495,95 +418,35 @@ pub struct BlockBoundsCache<'a> {
/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. /// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new()) bounds_of(d, e, depth, false, &mut cache.drawn)
} }
/// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. /// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new()) bounds_of(d, e, 0, true, &mut cache.extents)
} }
/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>) -> Bounds2 {
/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It
/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while
/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through
/// one viewport never answer for another. Two things a selection counts whatever the viewport
/// draws stay in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box the
/// drawing gives it, and a dimension by its definition points, which its block holds as points on
/// the layer Defpoints, so such a point counts in any block ([`point_on_defpoints`]).
pub struct ViewportBounds<'a> {
/// The layers frozen in the viewport.
frozen: &'a [String],
/// By block name and depth, the box of the block contents the viewport draws.
blocks: HashMap<(&'a str, usize), Contents<'a>>,
/// The same with no layer of the viewport left out: the box the drawing gives the contents,
/// which a clipped reference keeps.
in_drawing: HashMap<(&'a str, usize), Contents<'a>>,
}
impl<'a> ViewportBounds<'a> {
/// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere).
pub fn new(frozen: &'a [String]) -> Self {
ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() }
}
/// The layers frozen in the viewport.
pub fn frozen(&self) -> &'a [String] {
self.frozen
}
/// Whether the viewport leaves `part` out for its layer. `part` is an entity of the block
/// that an object the viewport draws is drawn from (a block reference, a dimension, a
/// multileader), and it is left out when its layer is frozen in the viewport, as in the
/// boxes above. A part on layer 0 never is: it takes the layer of the object, which the
/// caller has checked. What the drawing itself hides (a layer frozen for the whole drawing
/// or turned off) is not looked at here.
pub fn leaves_out(&self, part: &Entity) -> bool {
part.common.layer != "0" && frozen_in(self.frozen, &part.common.layer)
}
/// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the
/// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check.
pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing)
}
}
/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a
/// top-level annotative object measured as it draws.
fn bounds_of<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
off_counts: bool,
frozen: &[String],
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale. // A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 { if depth == 0 {
match d.anno_draw(e) { match d.anno_draw(e) {
crate::AnnoDraw::Plain => {} crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY, crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen), crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts),
} }
} }
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen) bounds_in(d, e, depth, blocks, off_counts)
} }
/// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw /// The bounds of a record kept as read that draws something: a proxy as its proxy graphics draw
/// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an /// (layer 0 in them is the proxy's layer), each at the next depth as a block's contents are, and an
/// OLE2FRAME as its frame. Measured through a viewport, the proxy graphics on a layer `frozen` /// OLE2FRAME as its frame.
/// there are left out as a block's parts are ([`in_block_visible`]), and a reference among them
/// takes its boxes from `blocks` and `in_drawing` as any other does ([`bounds_in`]).
fn unknown_bounds<'a>( fn unknown_bounds<'a>(
d: &'a Drawing, d: &'a Drawing,
u: &crate::Unknown, u: &crate::Unknown,
depth: usize, depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool, off_counts: bool,
frozen: &[String],
) -> Bounds2 { ) -> Bounds2 {
if u.graphics.is_empty() { if u.graphics.is_empty() {
return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points); return ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points);
@@ -593,8 +456,8 @@ fn unknown_bounds<'a>(
} }
u.graphics u.graphics
.iter() .iter()
.filter(|g| in_block_visible(d, g, off_counts, frozen)) .filter(|g| in_block_visible(d, g, off_counts))
.fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, in_drawing, off_counts, frozen))) .fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts)))
} }
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed, /// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
@@ -602,20 +465,8 @@ fn unknown_bounds<'a>(
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each /// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
/// definition per depth instead of one per reference (which grows exponentially with the nesting /// definition per depth instead of one per reference (which grows exponentially with the nesting
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its /// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in /// bounds must not stand in for a shallower reference to the same block (#706).
/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Contents<'a>>, off_counts: bool) -> Bounds2 {
/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen
/// layer: a measure through a viewport takes from it the box the drawing gives the block of a
/// clipped reference ([`drawing_contents`]). A measure with no frozen layer does not use it.
fn bounds_in<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Contents<'a>>,
in_drawing: &mut HashMap<(&'a str, usize), Contents<'a>>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
match &e.kind { match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(), EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY, EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
@@ -639,18 +490,9 @@ fn bounds_in<'a>(
let mut defs = None; let mut defs = None;
if let Some(blk) = d.block(&ins.block) { if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy()); let m = ins.transform(blk.base.xy());
let c = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen); let c = contents(d, blk, depth, blocks, off_counts);
defs = c.map(|c| &c.defs); defs = c.map(|c| &c.defs);
let mut inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins)); let inner = c.map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
// XCLIP: the reference app selects a clipped reference by its boundary whatever a
// viewport draws inside it, so a clipped reference keeps the box the drawing gives it.
// One that is not inverted and has a part drawn gets the boundary's box below as it is.
if !frozen.is_empty()
&& let Some(c) = ins.clip.as_ref().filter(|c| c.active())
&& (c.inverted || inner.is_empty())
{
inner = drawing_contents(d, blk, depth, off_counts, in_drawing).map_or(Bounds2::EMPTY, |c| c.in_reference(ins));
}
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) }; b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the // XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's). // block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -672,7 +514,7 @@ fn bounds_in<'a>(
} }
} }
for a in &ins.attribs { for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts, frozen) { if !a.invisible && layer_counts(d, attrib_layer(defs, a), off_counts) {
b = b.union(&match a.multiline_text() { b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m), Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()), None => text_box(&a.text, a.text.value.chars().count()),
@@ -709,7 +551,7 @@ fn bounds_in<'a>(
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension // Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
// block with branching or self-referencing children costs one pass per definition // block with branching or self-referencing children costs one pass per definition
// per depth, not one per reference (which grows exponentially) (CWE-400). // per depth, not one per reference (which grows exponentially) (CWE-400).
let inner = contents(d, blk, depth, blocks, in_drawing, off_counts, frozen).map_or(Bounds2::EMPTY, |c| c.geometry); let inner = contents(d, blk, depth, blocks, off_counts).map_or(Bounds2::EMPTY, |c| c.geometry);
// The block draws translated by the insertion point (group 12), so its bounds // The block draws translated by the insertion point (group 12), so its bounds
// move with it (#2634); the cache above keeps the block's own bounds. // move with it (#2634); the cache above keeps the block's own bounds.
let off = dm.insertion_point.xy(); let off = dm.insertion_point.xy();
@@ -728,7 +570,7 @@ fn bounds_in<'a>(
} }
if let Some(ins) = &m.block { if let Some(ins) = &m.block {
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) }; let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen)); b = b.union(&bounds_in(d, &be, depth, blocks, off_counts));
} }
b b
} }
@@ -748,7 +590,7 @@ fn bounds_in<'a>(
EntityKind::LwPolyline(p) => lwpolyline_bounds(p), EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
// A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its // A proxy measures as its proxy graphics draw. An OLE object's content is not drawn, but its
// frame is, so the frame counts (#2422). // frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, in_drawing, off_counts, frozen), EntityKind::Unknown(u) if !u.graphics.is_empty() || u.is_ole_frame() => unknown_bounds(d, u, depth, blocks, off_counts),
kind => { kind => {
let mut b = Bounds2::EMPTY; let mut b = Bounds2::EMPTY;
for p in kind.prims() { for p in kind.prims() {
@@ -1032,247 +874,6 @@ mod tests {
} }
} }
/// A viewport leaves a part of a block out for its layer when that layer is frozen in the
/// viewport, its name matched whatever its case. A part on layer 0 is never left out, also
/// where the viewport freezes layer 0: it takes the layer of the object drawn from the block.
/// A layer the drawing itself hides (frozen for the whole drawing, or turned off) is not the
/// viewport's to leave out, and a viewport that freezes no layer leaves nothing out.
#[test]
fn a_viewport_leaves_out_the_parts_on_its_frozen_layers() {
let part = |layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) });
let mut e = Entity::new(crate::Handle(1), kind);
e.common.layer = layer.into();
e
};
let frozen = ["hidden".to_string(), "0".to_string()];
let (through, plain) = (ViewportBounds::new(&frozen), ViewportBounds::new(&[]));
assert!(through.leaves_out(&part("Hidden")), "a layer frozen in the viewport, its name in another case");
assert!(!plain.leaves_out(&part("Hidden")), "the same part where no layer is frozen");
assert!(!through.leaves_out(&part("0")), "layer 0 takes the object's layer");
assert!(!through.leaves_out(&part("Other")), "a layer the viewport does not freeze");
}
/// Through a layout viewport the block contents on a layer frozen in it take no room: a part
/// of a reference, a part two blocks deep, a nested reference that is itself on that layer
/// (with everything in it), an attribute, the parts of the block a dimension or a multileader
/// draws (a reference nested in a dimension's block too), and the parts of an annotative
/// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn
/// of it. The layer's name is matched whatever its case. With no layer frozen
/// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity
/// the box a fresh one gives it.
#[test]
fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() };
let ins = |block: &str, layer: &str| {
let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block)));
e.common.layer = layer.into();
e
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut b = crate::Block::new(name);
for part in parts {
b.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(b));
};
// B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a
// reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden".
add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]);
add("N", vec![ins("B", "0")]);
add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]);
add("H", vec![line(1, 50.0, "Hidden")]);
// A reference to B with an attribute on "Hidden" at y = 70.
let mut tagged = ins("B", "0");
if let EntityKind::Insert(i) = &mut tagged.kind {
i.attribs.push(crate::Attrib {
tag: "T".into(),
text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) },
invisible: false,
constant: false,
prompt: String::new(),
props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() },
multiline: None,
modes: Default::default(),
});
}
// References to H clipped to a boundary around its line, and with that clip inverted: no
// part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B
// with the inverted clip: its line along y = 0 is drawn there.
let clip = |block: &str, inverted: bool| {
let mut e = ins(block, "0");
if let EntityKind::Insert(i) = &mut e.kind {
let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]);
i.clip = Some(crate::ClipBoundary { inverted, ..boundary });
}
e
};
let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true));
// An annotative reference to B: measured as it draws at the annotation scale, here 1:1.
let mut scaled = ins("B", "0");
scaled.common.anno_scales = vec![crate::AnnoScale::unit()];
// Dimensions that draw B and N, and a multileader that draws B.
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(3), kind)
};
let (dim, dim_nested) = (dimension("B"), dimension("N"));
let leader = Entity::new(
crate::Handle(4),
EntityKind::MLeader(crate::MLeader {
leaders: vec![vec![Vec3::ZERO]],
landing: Vec3::new(1.0, 0.0, 0.0),
dogleg: 0.45,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(reference("B")),
}),
);
let frozen = ["HIDDEN".to_string()];
let mut view = ViewportBounds::new(&frozen);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer");
assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep");
assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer");
assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty());
assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn");
let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0));
let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped));
assert_eq!((drawn.min, drawn.max), boundary);
assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary");
assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box");
assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too");
assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0);
assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer");
assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference");
assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws");
assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws");
assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws");
let clips = [clipped, clipped_inverted, clipped_partly];
let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips);
let all: Vec<Entity> = all.collect();
let mut plain = ViewportBounds::new(&[]);
for e in &all {
let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0));
assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max));
}
}
/// With the layer Defpoints frozen in the viewport, a point on that layer that is a part of a
/// block still counts: in the block of a reference, one block deeper, in the block of a
/// dimension, as its definition points are held, and in that of a dimension that is itself a
/// part of a block. Here the point lies far above all the rest. A line on Defpoints, a point
/// on another frozen layer and a line on one are left out. One [`ViewportBounds`] gives each of
/// them the box a fresh one gives it.
#[test]
fn a_viewport_keeps_the_points_on_defpoints_in_a_block() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let point = |handle: u64, y: f64, layer: &str| {
let mut e = Entity::new(crate::Handle(handle), EntityKind::Point(crate::Point { p: Vec3::new(5.0, y, 0.0), angle: 0.0 }));
e.common.layer = layer.into();
e
};
let ins = |block: &str| Entity::new(crate::Handle(9), EntityKind::Insert(crate::Insert { block: block.into(), ..crate::Insert::default() }));
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(8), kind)
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
d.ensure_layer("Defpoints");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut block = crate::Block::new(name);
for part in parts {
block.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(block));
};
// P: a line along y = 0 on layer 0, a point on Defpoints at y = 200, a line on Defpoints
// along y = 250 and a line on "Hidden" along y = 300. NP holds a reference to P, DP a
// dimension that draws P. H is P with the point on "Hidden".
add("P", vec![line(1, 0.0, "0"), point(2, 200.0, "Defpoints"), line(3, 250.0, "Defpoints"), line(4, 300.0, "Hidden")]);
add("NP", vec![ins("P")]);
add("DP", vec![dimension("P")]);
add("H", vec![line(1, 0.0, "0"), point(2, 200.0, "Hidden")]);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("P"), 0)), (0.0, 300.0));
let frozen = ["HIDDEN".to_string(), "defpoints".to_string()];
let mut view = ViewportBounds::new(&frozen);
assert_eq!(ys(view.entity_bounds(&d, &ins("P"))), (0.0, 200.0), "the point on Defpoints in a reference's block, not the lines");
assert_eq!(ys(view.entity_bounds(&d, &ins("NP"))), (0.0, 200.0), "the same one block deeper");
assert_eq!(view.entity_bounds(&d, &dimension("P")).max.y, 200.0, "a dimension's definition point");
assert_eq!(view.entity_bounds(&d, &ins("DP")).max.y, 200.0, "the same for a dimension in a block");
assert_eq!(ys(view.entity_bounds(&d, &ins("H"))), (0.0, 0.0), "a point on another frozen layer");
// Where the viewport freezes only the other layer, the line on Defpoints counts too.
let hidden = ["Hidden".to_string()];
assert_eq!(ys(ViewportBounds::new(&hidden).entity_bounds(&d, &ins("P"))), (0.0, 250.0));
for e in [ins("P"), ins("NP"), dimension("P"), ins("DP"), ins("H")] {
let (shared, fresh) = (view.entity_bounds(&d, &e), ViewportBounds::new(&frozen).entity_bounds(&d, &e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
}
}
/// A turned array of references reaches its side copies, not only the first and the last; /// A turned array of references reaches its side copies, not only the first and the last;
/// a hostile count measures only the copies that are drawn. /// a hostile count measures only the copies that are drawn.
#[test] #[test]
+3 -3
View File
@@ -31,8 +31,8 @@ pub use cadcraft_geom as geom;
pub use constraint::*; pub use constraint::*;
pub use entity::*; pub use entity::*;
pub use extents::{ pub use extents::{
BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts,
ole_frame_accepts, ole_frame_transform, point_on_defpoints, ole_frame_transform,
}; };
pub use format::Format; pub use format::Format;
pub use gdt::*; pub use gdt::*;
@@ -41,7 +41,7 @@ pub use names::{Named, NamedList, NamedMap};
pub use plotstyle::*; pub use plotstyle::*;
pub use plotter::*; pub use plotter::*;
pub use raster::{Raster, Rasters}; pub use raster::{Raster, Rasters};
pub use refedit::{RefEdit, WorkItem, XrefSource}; pub use refedit::{RefEdit, WorkItem};
pub use store::EntityStore; pub use store::EntityStore;
pub use tables::*; pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES}; pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
-33
View File
@@ -250,39 +250,6 @@ pub fn pattern_for(d: &Drawing, name: &str) -> Option<HatchPattern> {
Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p }) Some(if d.header.i64("MEASUREMENT", 0) == 1 { scaled_pattern(p, 25.4) } else { p })
} }
/// The pattern name of a user-defined hatch, as the DXF Reference writes it (group 2). Its families
/// are not a named pattern's: a hatch stores them at unit scale, turned by its angle and spaced by
/// its scale (groups 52, 41 and 77 of a DXF file), so [`user_defined_lines`] makes them for a file
/// that lists none (AutoCAD's own are written with 78 = 0).
pub const USER_PATTERN: &str = "_USER";
/// Whether `name` is a user-defined hatch's pattern name ([`USER_PATTERN`], in any case).
pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
/// Whether the scale can be used for hatch pattern lines.
pub fn is_supported_hatch_pattern_scale(scale: f64) -> bool {
scale.is_finite() && scale > MIN_HATCH_PATTERN_SCALE
}
/// The effective scale of a stored hatch. Use unit scale when its scale is unusable.
pub fn effective_hatch_pattern_scale(scale: f64) -> f64 {
if is_supported_hatch_pattern_scale(scale) { scale } else { 1.0 }
}
/// The line families of a user-defined hatch at unit scale, as a pattern definition has them: lines
/// along the hatch's angle, its scale apart, and with `double` a second family at right angles to
/// them. The hatch's angle turns the families and its scale spaces them, so a hatch of spacing
/// `s` and lines at `a` stores angle `a`, scale `s` and these families.
pub fn user_defined_lines(double: bool) -> Vec<PatternLine> {
let family = || PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 1.0), dashes: Vec::new() };
if double { vec![family(), PatternLine { angle: 90.0, ..family() }] } else { vec![family()] }
}
/// `p` with every length (origins, offsets, dashes) multiplied by `k`. /// `p` with every length (origins, offsets, dashes) multiplied by `k`.
fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern { fn scaled_pattern(mut p: HatchPattern, k: f64) -> HatchPattern {
for l in &mut p.lines { for l in &mut p.lines {
-30
View File
@@ -42,36 +42,6 @@ pub struct RefEdit {
/// Block objects taken out of the working set with their edits (block coordinates, the block /// Block objects taken out of the working set with their edits (block coordinates, the block
/// object's handle). /// object's handle).
pub released: Vec<Entity>, 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 { impl RefEdit {
-6
View File
@@ -728,11 +728,6 @@ pub struct Block {
/// The parameters of an associative array when this is an array block. /// The parameters of an associative array when this is an array block.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub array: Option<crate::ArrayParams>, 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. /// The load state of an external reference.
@@ -779,7 +774,6 @@ impl Block {
explodable: true, explodable: true,
units: 0, units: 0,
array: None, array: None,
xref_stamp: None,
} }
} }
} }
-62
View File
@@ -931,68 +931,6 @@ fn constant_values_count_in_extents_as_attmode_shows_them() {
assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one"); assert!(top(2, true) > 40.0, "ATTMODE 2 shows an invisible one");
} }
#[test]
fn aligned_and_fit_text_extents_span_their_two_points() {
// Drawn from the first point to the second whatever rotation is stored: Fit at its own height,
// Aligned at the height that keeps its proportions.
let ext = |halign: HAlign, second: Option<Vec3>| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt) = (halign, second);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d)
};
let left = ext(HAlign::Left, None);
// Along x to a far second point: both reach it; only Aligned grows taller.
let far = Some(Vec3::new(20.0, 0.0, 0.0));
let (fit, aligned) = (ext(HAlign::Fit, far), ext(HAlign::Aligned, far));
assert!((fit.1.x - 20.0).abs() < 1e-9 && (aligned.1.x - 20.0).abs() < 1e-9, "{fit:?} {aligned:?}");
assert!(fit.1.x > left.1.x + 10.0, "wider than the same text left-justified");
assert_eq!(fit.1.y, left.1.y, "Fit keeps its height");
assert!(aligned.1.y > left.1.y * 5.0, "Aligned scales its height with its width");
// Straight up: the line turns to run to the second point.
let up = ext(HAlign::Fit, Some(Vec3::new(0.0, 20.0, 0.0)));
assert!((up.1.y - 20.0).abs() < 1e-9 && up.1.x < 1.0 && up.0.x < -0.5, "{up:?}");
// No second point, or one on the first: placed like left-justified text.
assert_eq!(ext(HAlign::Fit, None), left);
assert_eq!(ext(HAlign::Aligned, Some(Vec3::ZERO)), left);
}
#[test]
fn aligned_text_extents_keep_the_proportions_of_a_narrow_width_factor() {
// The fonts shape with the width factor as stored, so a text ten times narrower fitted over
// the same span is drawn ten times taller: its extents grow with it.
let top = |width_factor: f64| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt, t.width_factor) = (HAlign::Aligned, Some(Vec3::new(20.0, 0.0, 0.0)), width_factor);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d).1.y
};
assert!(top(0.001) > top(0.01) * 5.0, "{} {}", top(0.001), top(0.01));
}
#[test]
fn aligned_and_fit_text_extents_follow_how_unusable_sizes_are_drawn() {
let ext = |halign: HAlign, height: f64, width_factor: f64| {
let mut t = plain_attrib("T").text;
t.value = "AB".into();
(t.halign, t.align_pt, t.height, t.width_factor) = (halign, Some(Vec3::new(1000.0, 0.0, 0.0)), height, width_factor);
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap();
extents_pair(&d)
};
// A height of 0 is drawn as a height of 1: Aligned text still spans its points and has room.
let flat = ext(HAlign::Aligned, 0.0, 1.0);
assert!((flat.1.x - 1000.0).abs() < 1e-9 && flat.1.y > flat.0.y, "{flat:?}");
assert_eq!(flat, ext(HAlign::Aligned, 1.0, 1.0));
// Fit text with a width factor of 0 is not stretched to the second point.
assert!(ext(HAlign::Fit, 1.0, 0.0).1.x < 100.0);
assert!((ext(HAlign::Fit, 1.0, 1.0).1.x - 1000.0).abs() < 1e-9);
}
#[test] #[test]
fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() { fn an_attribute_lies_on_the_layer_of_the_first_definition_of_its_tag() {
// Two definitions of one tag, in different case, on a frozen layer and on layer 0: an // Two definitions of one tag, in different case, on a frozen layer and on layer 0: an
File diff suppressed because it is too large Load Diff
+11 -69
View File
@@ -134,7 +134,7 @@ struct Ctx {
} }
/// The folder of the host drawing at `host` (a file path). /// The folder of the host drawing at `host` (a file path).
pub(crate) fn folder(host: Option<&Path>) -> Option<PathBuf> { fn folder(host: Option<&Path>) -> Option<PathBuf> {
let p = host?.parent()?; let p = host?.parent()?;
Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() }) Some(if p.as_os_str().is_empty() { PathBuf::from(".") } else { p.to_path_buf() })
} }
@@ -293,17 +293,8 @@ fn case_insensitive(p: &Path) -> Result<Option<PathBuf>, ()> {
Ok(out.is_file().then_some(out)) 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. /// Read a drawing file through the host's io hooks, counting its bytes against the load's total.
/// Also returns the [`Stamp`] of the bytes read: taken from the opened file, so it describes them fn read(file: &Path, cx: &mut Ctx) -> Result<Drawing, String> {
/// 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")?; let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
{ {
@@ -312,9 +303,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes); let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes);
let limit = MAX_XREF_BYTES.min(left); let limit = MAX_XREF_BYTES.min(left);
let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?; let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?;
let meta = f.metadata().map_err(|e| e.to_string())?; let len = f.metadata().map_err(|e| e.to_string())?.len();
let len = meta.len();
let before = stamp_of(&meta);
let too_big = || { let too_big = || {
if limit < MAX_XREF_BYTES { if limit < MAX_XREF_BYTES {
format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20) format!("the referenced files are larger than {} MB together", MAX_XREF_TOTAL_BYTES >> 20)
@@ -332,10 +321,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
return Err(too_big()); return Err(too_big());
} }
cx.bytes = cx.bytes.saturating_add(n); cx.bytes = cx.bytes.saturating_add(n);
let after = f.metadata().ok().as_ref().and_then(stamp_of); (hooks.read)(&bytes, &file.to_string_lossy())
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")] #[cfg(target_arch = "wasm32")]
{ {
@@ -344,33 +330,6 @@ fn read(file: &Path, cx: &mut Ctx) -> Result<(Drawing, Option<Stamp>, Vec<u8>),
} }
} }
/// 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 /// Load every xref of `d` that isn't unloaded from the paths saved in it; `host` is the drawing's
/// own path. /// own path.
pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> { pub(crate) fn load_all(d: &mut Drawing, host: Option<&str>) -> Vec<Outcome> {
@@ -434,14 +393,8 @@ 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()) }; let Some(path) = b.xref_path.clone() else { return (XrefStatus::Unresolved, "not an xref".into()) };
clear(d, &key); clear(d, &key);
let (status, detail) = match fetch(&path, host, chosen, cx, depth) { let (status, detail) = match fetch(&path, host, chosen, cx, depth) {
Ok((x, file, read_as)) => match import(d, &key, &x, cx) { Ok((x, file)) => match import(d, &key, &x, cx) {
Ok(()) => { Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()),
// 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) => { Err(e) => {
// Whatever made it in before the failure goes again. A fetch that failed imported // 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. // nothing, so it doesn't pay for a second scan of the block table.
@@ -456,13 +409,7 @@ 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. /// Read the drawing referenced as `path` and load its own attached xrefs into it.
fn fetch( fn fetch(path: &str, host: Option<&Path>, chosen: bool, cx: &mut Ctx, depth: usize) -> Result<(Drawing, PathBuf), (XrefStatus, String)> {
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()); let unresolved = |m: &str| (XrefStatus::Unresolved, m.to_string());
if depth >= MAX_BLOCK_DEPTH { if depth >= MAX_BLOCK_DEPTH {
return Err(unresolved("xrefs are nested too deeply")); return Err(unresolved("xrefs are nested too deeply"));
@@ -476,7 +423,7 @@ fn fetch(
return Err(unresolved("too many referenced files")); return Err(unresolved("too many referenced files"));
} }
cx.files += 1; cx.files += 1;
let (mut x, read_as, _) = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?; let mut x = read(&file, cx).map_err(|e| (XrefStatus::Unresolved, format!("{}: {e}", file.to_string_lossy())))?;
cx.chain.push(canon); cx.chain.push(canon);
let nested: Vec<String> = 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(); x.blocks.values().filter(|b| b.xref_path.is_some() && !b.xref_overlay && !b.name.contains('|')).map(|b| b.name.clone()).collect();
@@ -487,20 +434,15 @@ fn fetch(
} }
} }
cx.chain.pop(); cx.chain.pop();
Ok((x, file, read_as)) Ok((x, file))
}
/// 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 /// 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 /// 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). /// host's settings, so layer changes survive a reload).
fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> { fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), String> {
cx.objects = cx.objects.saturating_add(object_count(x)); let count = x.blocks.values().fold(x.model.len(), |n, b| n.saturating_add(b.entities.len()));
cx.objects = cx.objects.saturating_add(count);
if cx.objects > MAX_XREF_OBJECTS { if cx.objects > MAX_XREF_OBJECTS {
return Err(format!("more than {MAX_XREF_OBJECTS} objects")); return Err(format!("more than {MAX_XREF_OBJECTS} objects"));
} }
+22
View File
@@ -343,6 +343,11 @@ fn eq_variants(o: &TanObj) -> Vec<Eq3> {
/// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations). /// Circle tangent to three objects, nearest the pick points (Newton on all sign combinations).
pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> { 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 [(o1, p1), (o2, p2), (o3, p3)] = objs;
let mut starts: Vec<[f64; 3]> = Vec::new(); let mut starts: Vec<[f64; 3]> = Vec::new();
let cen = (p1 + p2 + p3) / 3.0; let cen = (p1 + p2 + p3) / 3.0;
@@ -350,6 +355,20 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
starts.push([cen.x, cen.y, rad.max(1e-3)]); starts.push([cen.x, cen.y, rad.max(1e-3)]);
if let Some(c) = Circle::from_3_points(p1, p2, p3) { if let Some(c) = Circle::from_3_points(p1, p2, p3) {
starts.push([c.center.x, c.center.y, c.radius]); 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 mut best: Option<(f64, Circle)> = None;
let scale = rad.max(p1.dist(p2)).max(1e-6); let scale = rad.max(p1.dist(p2)).max(1e-6);
@@ -379,6 +398,9 @@ pub fn ttt(objs: [(TanObj, Vec2); 3]) -> Option<Circle> {
continue; continue;
} }
let c = Circle::new(Vec2::new(x[0], x[1]), x[2]); let c = Circle::new(Vec2::new(x[0], x[1]), x[2]);
if !ok(&c) {
continue;
}
let sc = score(&c, &objs); let sc = score(&c, &objs);
if best.is_none_or(|(b, _)| sc < b - 1e-12) { if best.is_none_or(|(b, _)| sc < b - 1e-12) {
best = Some((sc, c)); best = Some((sc, c));
+74 -5
View File
@@ -2,6 +2,7 @@ use super::{
Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number, Accept, Arc, Circle, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, added, arc, bad, circle, f64_req, line, number,
point_param, size_param, point_param, size_param,
}; };
use crate::snap;
pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn run_circle(s: &mut Session, p: &Value) -> Result<Value> {
let c = if let Some(center) = point_param(p, "center") { let c = if let Some(center) = point_param(p, "center") {
@@ -51,6 +52,8 @@ pub(super) fn run_arc(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) struct CircleM { pub(super) struct CircleM {
mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR mode: u8, // 0 center-radius, 1 = 3P, 2 = 2P, 3 = TTR
pts: Vec<Vec2>, 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, diameter: bool,
/// The `Ttr` option hands over to the tangent-circle machine. /// The `Ttr` option hands over to the tangent-circle machine.
delegate: Option<Box<dyn Interactive>>, delegate: Option<Box<dyn Interactive>>,
@@ -69,18 +72,22 @@ impl Interactive for CircleM {
match (self.mode, n) { match (self.mode, n) {
(0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]), (0, 0) => Prompt::new("Specify center point for circle", Accept::POINT).kw(&["3P", "2P", "Ttr (tan tan radius)"]),
(0, _) if self.diameter => { (0, _) if self.diameter => {
Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance() Prompt::new("Specify diameter of circle", Accept::POINT_OR_NUMBER).base_opt(self.pts.first().copied()).distance().deferred()
} }
(0, _) => { (0, _) => {
let p = let p = Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER)
Prompt::new("Specify radius of circle", Accept::POINT_OR_NUMBER).kw(&["Diameter"]).base_opt(self.pts.first().copied()).distance(); .kw(&["Diameter"])
.base_opt(self.pts.first().copied())
.distance()
.deferred();
if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p } if last_r > 0.0 { p.default(format!("{last_r:.4}")) } else { p }
} }
(1, k) => Prompt::new( (1, k) => Prompt::new(
["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""), ["Specify first point on circle", "Specify second point on circle", "Specify third point on circle"].get(k).copied().unwrap_or(""),
Accept::POINT, Accept::POINT,
) )
.base_opt(self.pts.last().copied()), .base_opt(self.pts.last().copied())
.deferred(),
(2, k) => Prompt::new( (2, k) => Prompt::new(
if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" }, if k == 0 { "Specify first end point of circle's diameter" } else { "Specify second end point of circle's diameter" },
Accept::POINT, Accept::POINT,
@@ -120,7 +127,14 @@ impl Interactive for CircleM {
let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) }; let r = if self.diameter { c.dist(*e) / 2.0 } else { c.dist(*e) };
Some(Circle::new(*c, r)) Some(Circle::new(*c, r))
} }
1 if self.pts.len() == 3 => Circle::from_3_points(self.pts[0], self.pts[1], self.pts[2]), 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()));
}
},
2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])), 2 if self.pts.len() == 2 => Some(Circle::from_2_points(self.pts[0], self.pts[1])),
_ => None, _ => None,
}; };
@@ -130,6 +144,29 @@ impl Interactive for CircleM {
} }
Ok(Step::Continue) 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 => { 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 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 }; let r = if self.diameter { v / 2.0 } else { v };
@@ -174,6 +211,38 @@ 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<()> { fn finish_circle(s: &mut Session, c: Circle) -> Result<()> {
s.add_entity(circle(c.center, c.radius))?; s.add_entity(circle(c.center, c.radius))?;
s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius); s.doc_mut()?.header.set_f64("CIRCLERAD", c.radius);
+5 -7
View File
@@ -853,13 +853,12 @@ fn adopt_source_group(out: &std::fs::File, src: &std::fs::Metadata) -> std::io::
/// ([`crate::atomic_write::write_atomic_with`]). Nothing /// ([`crate::atomic_write::write_atomic_with`]). Nothing
/// to keep when there is no file yet. A file that doesn't look like a drawing /// 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. /// ([`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"))] #[cfg(not(target_arch = "wasm32"))]
pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> { fn backup(path: &std::path::Path) -> std::io::Result<()> {
let mut src = match std::fs::File::open(path) { let mut src = match std::fs::File::open(path) {
Ok(f) if f.metadata()?.is_file() => f, Ok(f) if f.metadata()?.is_file() => f,
Ok(_) => return Ok(false), Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e), Err(e) => return Err(e),
}; };
let (head, tail, len) = ends(&mut src)?; let (head, tail, len) = ends(&mut src)?;
@@ -868,7 +867,7 @@ pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
// the roots (or to another computer) isn't looked at. // the roots (or to another computer) isn't looked at.
if !backup_replaced(&head, &tail, len, std::fs::symlink_metadata(&bak).is_ok()) { 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()); log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display());
return Ok(false); return Ok(());
} }
// The backup is no more readable than the drawing, nor than the .bak it replaces (a private // 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 // 0600 drawing or .bak stays private). The mode is set as the new file is created, so a
@@ -894,8 +893,7 @@ pub(crate) fn backup(path: &std::path::Path) -> std::io::Result<bool> {
} }
std::io::Write::write_all(out, &head)?; std::io::Write::write_all(out, &head)?;
std::io::copy(&mut src, out).map(|_| ()) 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 /// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps
+4 -90
View File
@@ -1,7 +1,7 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`). //! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle}; use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3}; use cadcraft_geom::{Mat3, Vec2};
use serde_json::{Value, json}; use serde_json::{Value, json};
use super::curves; use super::curves;
@@ -78,70 +78,6 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() })) Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
} }
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
};
let z = match kind {
EntityKind::Line(l) => match index {
0 => Some(l.a.z),
1 => Some((l.a.z + l.b.z) * 0.5),
2 => Some(l.b.z),
_ => None,
},
EntityKind::Point(p) => (index == 0).then_some(p.p.z),
EntityKind::Circle(c) => (index < 5).then_some(c.center.z),
EntityKind::Arc(a) => (index < 4).then_some(a.center.z),
EntityKind::Ellipse(e) => (index < 5).then_some(e.center.z),
EntityKind::LwPolyline(p) => (index < kind.grips().len()).then_some(p.elevation),
EntityKind::Polyline3d(p) => p.points.get(index).map(|q| q.z),
EntityKind::Helix(h) => match index {
0 => Some(h.center.z),
1 => Some(h.start_point().z),
2 => Some(h.end_point().z),
_ => None,
},
EntityKind::Ray(r) | EntityKind::XLine(r) => match index {
0 => Some(r.base.z),
1 => Some(r.base.z + r.dir.z),
_ => None,
},
EntityKind::Text(t) => (index == 0).then(|| text_z(t)),
EntityKind::MText(t) => (index == 0).then_some(t.insert.z),
EntityKind::AttDef(a) => (index == 0).then(|| text_z(&a.text)),
EntityKind::Insert(i) => {
if index == 0 {
Some(i.insert.z)
} else {
i.grip_attribs().nth(index - 1).map(|(_, a)| text_z(&a.text))
}
}
EntityKind::Dimension(d) => match index {
0 => Some(d.p13.z),
1 => Some(d.p14.z),
2 => Some(d.defpt.z),
3 => Some(d.text_mid.z),
_ => None,
},
EntityKind::MLine(m) => m.vertices.get(index).map(|v| v.p.z),
EntityKind::Leader(l) => l.vertices.get(index).map(|v| v.z),
EntityKind::MLeader(m) => m.leaders.iter().flatten().map(|v| v.z).chain(std::iter::once(m.landing.z)).nth(index),
EntityKind::Hatch(h) => (index == 0).then_some(h.elevation),
EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.get(index).map(|c| c.z),
EntityKind::Face3d(f) => f.corners.get(index).map(|c| c.z),
EntityKind::PolyfaceMesh(m) => m.vertices.get(index).map(|v| v.z),
EntityKind::Viewport(v) => (index < 4).then_some(v.center.z),
EntityKind::Image(i) => (index == 0).then_some(i.insert.z),
EntityKind::Table(t) => (index < kind.grips().len()).then_some(t.insert.z),
EntityKind::Tolerance(t) => (index == 0).then_some(t.insert.z),
EntityKind::Spline(_) | EntityKind::Region(_) | EntityKind::Wipeout(_) | EntityKind::Unknown(_) => None,
};
z.filter(|v| v.is_finite())
}
/// Base point: `base`, or grip `index` of `baseHandle` (default: the first target). /// Base point: `base`, or grip `index` of `baseHandle` (default: the first target).
fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2> { fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2> {
if let Some(b) = point_param(p, "base") { if let Some(b) = point_param(p, "base") {
@@ -155,27 +91,6 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip")) g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
} }
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
if let Some(b) = point_param(p, "base") {
return match p.get("base").and_then(|v| v.get(2)) {
Some(z) => z.as_f64().filter(|v| v.is_finite()).map(|z| Vec3::new(b.x, b.y, z)).ok_or_else(|| bad(cmd, "`base` Z must be a number")),
None => Ok(super::modify::at_elevation(s, b)),
};
}
let h = curves::handle_param(p, "baseHandle")
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
}
fn apply(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Value> { fn apply(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Value> {
let r = super::modify::transform_entities(s, hs, m, copy)?; let r = super::modify::transform_entities(s, hs, m, copy)?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() })) Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
@@ -337,17 +252,16 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> { fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?; let hs = targets(s, p)?;
// Why: Selected grip is the SCALE base point and must remain stationary in all three coordinates. let base = base_point(s, "grip.scale", p, &hs)?;
let base = base_point_3d(s, "grip.scale", p, &hs)?;
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) { let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f, Some(f) if f > 1e-12 => f,
Some(_) => return Err(bad("grip.scale", "factor must be positive")), Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => { None => {
let f = base.xy().dist(point_req("grip.scale", p, "to")?); let f = base.dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) } if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
} }
}; };
let r = super::modify::scale_entities(s, &hs, base, f, bool_or(p, "copy", false))?; let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() })) Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
} }
+11 -13
View File
@@ -9,7 +9,7 @@
use std::sync::Arc; use std::sync::Arc;
use cadcraft_doc::{Drawing, EntityKind, Handle}; use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3}; use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips; use super::gripcmds::stretch_grips;
use super::helpers::line; use super::helpers::line;
@@ -47,7 +47,6 @@ pub(crate) struct GripEdit {
/// selection that the view being edited shows. /// selection that the view being edited shows.
targets: Vec<Handle>, targets: Vec<Handle>,
base: Vec2, base: Vec2,
base_z: Option<f64>,
mode: GripMode, mode: GripMode,
copy: bool, copy: bool,
ask: Ask, ask: Ask,
@@ -85,7 +84,6 @@ impl GripEdit {
picking: false, picking: false,
targets: Vec::new(), targets: Vec::new(),
base: Vec2::ZERO, base: Vec2::ZERO,
base_z: None,
mode: GripMode::Stretch, mode: GripMode::Stretch,
copy: false, copy: false,
ask: Ask::Mode, ask: Ask::Mode,
@@ -111,7 +109,6 @@ impl GripEdit {
} }
if self.hot.is_empty() { if self.hot.is_empty() {
self.base = p; self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.targets.push(h); self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x))); self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) { } else if !self.targets.contains(&h) {
@@ -253,13 +250,7 @@ impl GripEdit {
return Err(other("Invalid point.")); return Err(other("Invalid point."));
} }
let before = s.state()?.doc.clone(); let before = s.state()?.doc.clone();
// Why: Selected grip is the SCALE base point and must remain stationary in all three let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
// coordinates; fall back to ELEVATION only when the base has no stored 3D Z.
let base = match self.base_z.filter(|z| z.is_finite()) {
Some(z) => Vec3::new(self.base.x, self.base.y, z),
None => at_elevation(s, self.base),
};
let changed = !scale_entities(s, &self.targets, base, f, self.copy)?.is_empty();
self.finish_edit(before, changed) self.finish_edit(before, changed)
} }
@@ -308,7 +299,7 @@ impl GripEdit {
s.echo(self.label()); s.echo(self.label());
Ok(Step::Continue) Ok(Step::Continue)
} }
Input::Point(p) | Input::Deferred(crate::snap::Deferred { at: p, .. }) => { Input::Point(p) => {
if self.mode == GripMode::Scale { if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p)) self.edit_scale(s, self.base.dist(p))
} else { } else {
@@ -316,6 +307,14 @@ impl GripEdit {
self.edit(s, p, m) self.edit(s, p, m)
} }
} }
Input::Deferred(d) => {
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
}
Input::Text(t) => match self.mode { Input::Text(t) => match self.mode {
GripMode::Rotate => { GripMode::Rotate => {
let a = s.angle_settings().rotation(&t).filter(|a| a.is_finite()).ok_or_else(|| other("Requires an angle or point."))?; let a = s.angle_settings().rotation(&t).filter(|a| a.is_finite()).ok_or_else(|| other("Requires an angle or point."))?;
@@ -459,7 +458,6 @@ impl Interactive for GripEdit {
Ask::Base => match i { Ask::Base => match i {
Input::Point(p) => { Input::Point(p) => {
self.base = p; self.base = p;
self.base_z = None;
self.ask = Ask::Mode; self.ask = Ask::Mode;
Ok(Step::Continue) Ok(Step::Continue)
} }
+19 -409
View File
@@ -7,7 +7,6 @@ pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices}; pub use patfile::{PatternChoice, pattern_choices};
use cadcraft_color::Color; use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds}; use cadcraft_doc::{Drawing, Entity, EntityKind, Gradient, Handle, Hatch, HatchLoop, Space, entity_bounds};
use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -27,24 +26,10 @@ use super::has_doc;
pub(crate) use assoc::update as refill_associative; pub(crate) use assoc::update as refill_associative;
pub use pick::{HatchPicks, PickMode}; pub use pick::{HatchPicks, PickMode};
/// HATCH's parameters, for its JSON form and its catalog entry (the same for -HATCH).
const HATCH_PARAMS: &str = "{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close";
pub fn specs() -> Vec<CommandSpec> { pub fn specs() -> Vec<CommandSpec> {
vec![ vec![
// An AutoLISP routine's `(command …)` call answers HATCH's published command-line questions CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))),
// (pattern, how it is drawn, then the boundary). A person, and a script's own HATCH line, CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))),
// get the interface's dialog, or the prompts of AutoCAD's -HATCH when it is off: a script
// keeps picking the boundary first as it always has.
CommandSpec::new("hatch", "Hatch...", run_hatch)
.menu(&["Draw", "Hatch..."])
.alias(&["h", "bh"])
.params(HATCH_PARAMS)
.interactive(|s| Ok(Box::new(HatchM::new(s, false, s.lisp_program_input())))),
// -HATCH: the command-line form, a script's too. Its own id, so a dashed start takes its
// prompts and never the HATCH sequence above.
CommandSpec::new("-hatch", "Hatch", run_hatch).params(HATCH_PARAMS).interactive(|s| Ok(Box::new(HatchM::new(s, false, false)))),
CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true, false)))),
CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))),
CommandSpec::new("region", "Region", run_region) CommandSpec::new("region", "Region", run_region)
.menu(&["Draw", "Region"]) .menu(&["Draw", "Region"])
@@ -342,12 +327,7 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
struct HatchSettings { struct HatchSettings {
pattern: String, pattern: String,
scale: f64, scale: f64,
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
user_spacing: f64,
angle: f64, angle: f64,
/// A user-defined pattern is doubled ("Double hatch area?", DXF group 77): a second family of
/// lines at right angles to the first.
double: bool,
gradient: Option<Gradient>, gradient: Option<Gradient>,
associative: bool, associative: bool,
/// HPSEPARATE: one hatch per picked point or selected object. /// HPSEPARATE: one hatch per picked point or selected object.
@@ -372,13 +352,10 @@ impl HatchSettings {
angle: f64_or(p, "angle", 0.0).to_radians(), angle: f64_or(p, "angle", 0.0).to_radians(),
centered: bool_or(p, "centered", true), centered: bool_or(p, "centered", true),
}); });
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
HatchSettings { HatchSettings {
pattern, pattern,
scale, scale: f64_or(p, "scale", hdr.1).max(1e-9),
user_spacing: scale,
angle: p.get("angle").and_then(Value::as_f64).map(f64::to_radians).unwrap_or(hdr.2), angle: p.get("angle").and_then(Value::as_f64).map(f64::to_radians).unwrap_or(hdr.2),
double: false,
gradient: g, gradient: g,
associative: bool_or(p, "associative", s.doc().map_or(true, |d| d.header.i64("HPASSOC", 1) != 0)), associative: bool_or(p, "associative", s.doc().map_or(true, |d| d.header.i64("HPASSOC", 1) != 0)),
separate: bool_or(p, "separate", s.doc().is_ok_and(|d| d.header.i64("HPSEPARATE", 0) != 0)), separate: bool_or(p, "separate", s.doc().is_ok_and(|d| d.header.i64("HPSEPARATE", 0) != 0)),
@@ -402,22 +379,19 @@ impl HatchSettings {
loops.iter_mut().for_each(|l| l.sources.clear()); loops.iter_mut().for_each(|l| l.sources.clear());
} }
let solid = self.gradient.is_some() || self.pattern == "SOLID"; let solid = self.gradient.is_some() || self.pattern == "SOLID";
let user_defined = cadcraft_doc::library::is_user_pattern(&self.pattern);
EntityKind::Hatch(Hatch { EntityKind::Hatch(Hatch {
pattern: if self.gradient.is_some() { "SOLID".into() } else { self.pattern.clone() }, pattern: if self.gradient.is_some() { "SOLID".into() } else { self.pattern.clone() },
solid, solid,
origin: self.origin_mode.origin(&loops, self.origin), origin: self.origin_mode.origin(&loops, self.origin),
loops, loops,
scale: if user_defined { self.user_spacing } else { self.scale }, scale: self.scale,
angle: self.angle, angle: self.angle,
associative: self.associative, associative: self.associative,
style: self.style, style: self.style,
elevation: 0.0, elevation: 0.0,
gradient: self.gradient.clone(), gradient: self.gradient.clone(),
background: None, background: None,
// A user-defined hatch's families come from its angle, spacing and double flag, not pattern_lines: patfile::lines_for(&self.pattern),
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
}) })
} }
} }
@@ -608,12 +582,6 @@ fn pattern_exists(name: &str) -> bool {
cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some() cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some()
} }
/// Whether `t` answers the pattern prompt with the user-defined form (U, User, User defined), as
/// AutoCAD's HATCH takes it from an AutoLISP routine.
fn user_pattern_keyword(t: &str) -> bool {
matches!(t.trim().to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "u" | "user" | "userdefined")
}
/// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded /// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded
/// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ). /// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ).
pub(crate) fn pattern_named(name: &str) -> Option<String> { pub(crate) fn pattern_named(name: &str) -> Option<String> {
@@ -631,22 +599,11 @@ enum HatchAsk {
Pattern, Pattern,
Scale, Scale,
Angle, Angle,
/// The user-defined pattern's line angle: the same answer as [`HatchAsk::Angle`], asked as
/// AutoCAD's user-defined hatch asks it.
UserAngle,
/// The user-defined pattern's spacing between its lines (stored as the hatch's scale).
Spacing,
/// "Double hatch area?": a second family of lines at right angles.
Double,
Origin, Origin,
} }
struct HatchM { struct HatchM {
gradient: bool, gradient: bool,
/// An AutoLISP routine's `(command …)` call started HATCH ([`Session::lisp_program_input`]): the
/// published command-line sequence (the pattern or the user-defined form, then its values, then the
/// objects) rather than a boundary picked first, as a person and a script's own HATCH line do.
legacy: bool,
settings: HatchSettings, settings: HatchSettings,
/// Loops by pick (one hatch each when separate). /// Loops by pick (one hatch each when separate).
loops: Vec<Vec<HatchLoop>>, loops: Vec<Vec<HatchLoop>>,
@@ -659,10 +616,9 @@ struct HatchM {
} }
impl HatchM { impl HatchM {
fn new(s: &Session, gradient: bool, legacy: bool) -> Self { fn new(s: &Session, gradient: bool) -> Self {
HatchM { HatchM {
gradient, gradient,
legacy: legacy && !gradient,
settings: HatchSettings::from(s, &Value::Null, gradient), settings: HatchSettings::from(s, &Value::Null, gradient),
loops: Vec::new(), loops: Vec::new(),
asking: None, asking: None,
@@ -692,29 +648,14 @@ impl HatchM {
fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result<bool> { fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result<bool> {
match a { match a {
HatchAsk::Pattern => { HatchAsk::Pattern => {
let t = t.trim(); let up = match patfile::typed_file(s, t.trim()) {
// "?": the patterns there are, as AutoCAD lists them; the pattern is asked again.
if t == "?" {
s.echo(format!("Available patterns: {}", patfile::names().join(", ")));
return Ok(false);
}
// The user-defined form asks for its lines next, not a named pattern's scale and angle.
if self.legacy && user_pattern_keyword(t) {
self.settings.pattern = cadcraft_doc::library::USER_PATTERN.to_string();
self.settings.user_spacing = s.last_used.hatch_spacing;
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let up = match patfile::typed_file(s, t) {
// Nothing loaded from it: the pattern is asked again. // Nothing loaded from it: the pattern is asked again.
Some(n) if n.is_empty() => return Ok(false), Some(n) if n.is_empty() => return Ok(false),
Some(n) => n, Some(n) => n,
None => t.to_ascii_uppercase(), None => t.trim().to_ascii_uppercase(),
}; };
if pattern_exists(&up) { if pattern_exists(&up) {
self.settings.pattern = up.clone(); self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
s.doc_mut()?.header.set_str("HPNAME", &up); s.doc_mut()?.header.set_str("HPNAME", &up);
} else { } else {
s.echo(format!("Unknown pattern {up}. Available: {}", patfile::names().join(", "))); s.echo(format!("Unknown pattern {up}. Available: {}", patfile::names().join(", ")));
@@ -722,35 +663,16 @@ impl HatchM {
} }
} }
HatchAsk::Scale => { HatchAsk::Scale => {
let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { return Ok(false) };
s.echo("Value must be positive and nonzero.");
return Ok(false);
};
s.doc_mut()?.header.set_f64("HPSCALE", v);
self.settings.scale = v; self.settings.scale = v;
s.doc_mut()?.header.set_f64("HPSCALE", v);
} }
HatchAsk::Spacing => { HatchAsk::Angle => {
let Some(spacing) = super::machines::number(t).filter(|v| is_supported_hatch_pattern_scale(*v)) else {
s.echo(format!("Hatch spacing must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units."));
return Ok(false);
};
self.settings.user_spacing = spacing;
s.last_used.hatch_spacing = spacing;
}
HatchAsk::Angle | HatchAsk::UserAngle => {
// Turns the pattern from the X axis (not from ANGBASE), clockwise when ANGDIR is 1. // Turns the pattern from the X axis (not from ANGBASE), clockwise when ANGDIR is 1.
let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) else { return Ok(false) }; let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) else { return Ok(false) };
self.settings.angle = a; self.settings.angle = a;
s.doc_mut()?.header.set_f64("HPANG", a); s.doc_mut()?.header.set_f64("HPANG", a);
} }
HatchAsk::Double => {
self.settings.double = match t.trim().to_ascii_lowercase().as_str() {
"y" | "yes" => true,
"n" | "no" => false,
_ => return Ok(false),
};
s.last_used.hatch_double = self.settings.double;
}
HatchAsk::Origin => { HatchAsk::Origin => {
let mode = match t { let mode = match t {
"Bottom left" => OriginMode::BottomLeft, "Bottom left" => OriginMode::BottomLeft,
@@ -766,27 +688,15 @@ impl HatchM {
Ok(true) Ok(true)
} }
/// The angle prompt `msg` with the current angle as its default, offered as it would be typed.
fn angle_prompt(&self, s: &Session, msg: &str) -> Prompt {
let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
// Offered as it would be typed: clockwise is positive when ANGDIR is 1.
let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle };
Prompt::new(msg, Accept::NUMBER).default(crate::units::format_angle(a, au, ap))
}
/// The sub-prompt that follows `a` (`taken`: its answer was taken). The Pattern option goes /// The sub-prompt that follows `a` (`taken`: its answer was taken). The Pattern option goes
/// on, as AutoCAD 2024's -HATCH Properties does, from the pattern name to its scale and then /// on, as AutoCAD 2024's -HATCH Properties does, from the pattern name to its scale and then
/// its angle (a solid fill has neither), and asks again for a pattern or a value it refused. /// its angle (a solid fill has neither), and asks again for a pattern or a value it refused.
/// The user-defined form goes instead to its lines' angle, their spacing and the double answer.
fn after(&self, a: HatchAsk, taken: bool) -> Option<HatchAsk> { fn after(&self, a: HatchAsk, taken: bool) -> Option<HatchAsk> {
if !self.properties { if !self.properties {
return None; return None;
} }
match a { match a {
_ if !taken => Some(a), _ if !taken => Some(a),
HatchAsk::Pattern if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) => Some(HatchAsk::UserAngle),
HatchAsk::UserAngle => Some(HatchAsk::Spacing),
HatchAsk::Spacing => Some(HatchAsk::Double),
HatchAsk::Pattern if self.settings.pattern != "SOLID" => Some(HatchAsk::Scale), HatchAsk::Pattern if self.settings.pattern != "SOLID" => Some(HatchAsk::Scale),
HatchAsk::Scale => Some(HatchAsk::Angle), HatchAsk::Scale => Some(HatchAsk::Angle),
_ => None, _ => None,
@@ -805,13 +715,6 @@ impl Interactive for HatchM {
self.settings.scale, self.settings.scale,
self.settings.angle.to_degrees() self.settings.angle.to_degrees()
)); ));
if self.legacy {
// A routine answers the published questions first: the pattern, how it is drawn, then the
// boundary objects. A person picks the boundary first, and so does a script's own line.
self.asking = Some(HatchAsk::Pattern);
self.properties = true;
self.selecting = true;
}
Ok(Step::Continue) Ok(Step::Continue)
} }
fn prompt(&self, s: &Session) -> Prompt { fn prompt(&self, s: &Session) -> Prompt {
@@ -821,26 +724,17 @@ impl Interactive for HatchM {
let p = Prompt::new("Enter a pattern name", Accept::TEXT) let p = Prompt::new("Enter a pattern name", Accept::TEXT)
.default(self.settings.pattern.clone()) .default(self.settings.pattern.clone())
.picker(Picker::HatchPattern(self.settings.pattern.clone())); .picker(Picker::HatchPattern(self.settings.pattern.clone()));
return if self.gradient { return if self.gradient { p } else { p.kw(&["Solid"]) };
p
} else if self.legacy {
// The published command-line answers: a pattern, a solid fill, the user-defined
// form, or the pattern list.
p.kw(&["?", "Solid", "User defined"])
} else {
p.kw(&["Solid"])
};
} }
Some(HatchAsk::Scale) => { Some(HatchAsk::Scale) => {
return Prompt::new("Specify a scale for the hatch pattern", Accept::NUMBER).default(format!("{:.4}", self.settings.scale)); return Prompt::new("Specify a scale for the hatch pattern", Accept::NUMBER).default(format!("{:.4}", self.settings.scale));
} }
Some(HatchAsk::Angle) => return self.angle_prompt(s, "Specify an angle for the hatch pattern"), Some(HatchAsk::Angle) => {
Some(HatchAsk::UserAngle) => return self.angle_prompt(s, "Specify an angle for the hatch lines"), let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
Some(HatchAsk::Spacing) => { // Offered as it would be typed: clockwise is positive when ANGDIR is 1.
return Prompt::new("Specify a spacing between the lines", Accept::NUMBER).default(self.settings.user_spacing.to_string()); let a = if s.angle_settings().clockwise { -self.settings.angle } else { self.settings.angle };
} let d = crate::units::format_angle(a, au, ap);
Some(HatchAsk::Double) => { return Prompt::new("Specify an angle for the hatch pattern", Accept::NUMBER).default(d);
return Prompt::new("Double hatch area?", Accept::TEXT).kw(&["Yes", "No"]).default(if self.settings.double { "Y" } else { "N" });
} }
Some(HatchAsk::Origin) => return Prompt::new("Specify the pattern origin", Accept::POINT).kw(&ORIGIN_KW).default("Use current"), Some(HatchAsk::Origin) => return Prompt::new("Specify the pattern origin", Accept::POINT).kw(&ORIGIN_KW).default("Use current"),
None => {} None => {}
@@ -920,10 +814,7 @@ impl Interactive for HatchM {
self.asking = Some(HatchAsk::Pattern); self.asking = Some(HatchAsk::Pattern);
self.properties = !self.gradient; self.properties = !self.gradient;
} }
"sCale" => { "sCale" => self.asking = Some(HatchAsk::Scale),
let ask = if cadcraft_doc::library::is_user_pattern(&self.settings.pattern) { HatchAsk::Spacing } else { HatchAsk::Scale };
self.asking = Some(ask);
}
"Angle" => self.asking = Some(HatchAsk::Angle), "Angle" => self.asking = Some(HatchAsk::Angle),
"Origin" => self.asking = Some(HatchAsk::Origin), "Origin" => self.asking = Some(HatchAsk::Origin),
"sEparate" => { "sEparate" => {
@@ -991,16 +882,6 @@ mod tests {
d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some((e.handle.hex(), h.clone())) } else { None }).unwrap() d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some((e.handle.hex(), h.clone())) } else { None }).unwrap()
} }
/// How many hatches the drawing has.
fn hatch_count(s: &Session) -> usize {
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Hatch(_))).count()
}
/// The closed 4000 × 2000 polyline the older LISP routines draw before they hatch it.
fn lisp_rectangle(s: &mut Session) {
s.cmdline("(command \"_.pline\" '(0 0) '(4000 0) '(4000 2000) '(0 2000) \"_c\")").unwrap();
}
#[test] #[test]
fn hatchedit_pattern_replaces_gradient() { fn hatchedit_pattern_replaces_gradient() {
let mut s = Session::new(); let mut s = Session::new();
@@ -1110,277 +991,6 @@ mod tests {
s.cancel(); s.cancel();
} }
/// HATCH started by a LISP routine takes the published command-line answers in order: the
/// pattern name, its scale and angle, then the boundary objects (issue #3498).
#[test]
fn lisp_hatch_takes_pattern_scale_and_angle_then_the_objects() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(hatch_count(&s), 1);
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.loops.len()), ("DOTS", 1));
assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale);
assert!(h.angle.abs() < 1e-12, "{}", h.angle);
}
/// The user-defined answer (U) asks for the lines' angle, their spacing and whether to double
/// them, as AutoCAD's HATCH does, and makes one hatch of the selection.
#[test]
fn lisp_user_defined_hatch_takes_angle_spacing_and_double() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_n\" \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(hatch_count(&s), 1);
let h = only_hatch(&s).1;
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!(!h.solid);
assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale);
assert_eq!(h.pattern_lines.len(), 1, "not doubled");
let absolute = h.pattern_lines[0].angle + h.angle.to_degrees();
assert!((absolute - 45.0).abs() < 1e-9, "lines at {absolute} degrees");
}
/// A doubled user-defined hatch has a second family of lines at right angles to the first.
#[test]
fn a_doubled_user_defined_hatch_has_a_second_family_at_right_angles() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert_eq!(h.pattern_lines.len(), 2, "double hatch area: two families");
let absolute = |i: usize| h.pattern_lines[i].angle + h.angle.to_degrees();
assert!((absolute(1) - absolute(0) - 90.0).abs() < 1e-9, "{} and {}", absolute(0), absolute(1));
}
/// Enter at each question takes its default: the current pattern, scale and angle (the
/// user-defined form's angle, spacing and double flag too).
#[test]
fn lisp_hatch_enter_takes_the_current_values() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"\" \"\" \"\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.scale, h.angle), ("ANSI31", 1.0, 0.0));
// The user-defined questions too: ANSI31 is replaced, the current angle and spacing kept,
// and "Double hatch area?" defaults to No.
s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\" \"\" \"_l\" \"\")").unwrap();
let h = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None })
.find(|h| h.pattern == cadcraft_doc::library::USER_PATTERN)
.unwrap();
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!((h.scale - 1.0).abs() < 1e-12 && h.angle.abs() < 1e-12, "{} {}", h.scale, h.angle);
assert_eq!(h.pattern_lines.len(), 1, "not doubled");
}
#[test]
fn lisp_user_hatch_reads_spacing_and_double_across_drawings() {
let mut s = Session::new();
s.cmdline("(setvar \"HPSPACE\" 12.5)").unwrap();
s.cmdline("(setvar \"HPDOUBLE\" 1.0)").unwrap();
s.new_drawing(false);
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" \"\" \"\")").unwrap();
assert!(s.prompt_text().ends_with("<Y>:"), "{}", s.prompt_text());
for answer in ["", "_l", ""] {
s.cmdline(answer).unwrap();
}
let h = only_hatch(&s).1;
assert_eq!((h.scale, h.pattern_lines.len()), (12.5, 2));
}
#[test]
fn lisp_user_hatch_answers_leave_named_scale_unchanged() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(setvar \"HPSCALE\" 2.0)").unwrap();
s.cmdline("(command \"_.hatch\" \"_u\" 45 10 \"_y\" \"_l\" \"\")").unwrap();
assert_eq!(crate::sysvars::get(&s, "HPSCALE"), Some(json!(2.0)));
assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(10.0)));
assert_eq!(crate::sysvars::get(&s, "HPDOUBLE"), Some(json!(1)));
}
/// Solid asks neither a scale nor an angle, as it never has.
#[test]
fn lisp_hatch_solid_takes_no_scale_or_angle() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_s\" \"_l\" \"\")").unwrap();
let h = only_hatch(&s).1;
assert!(h.solid);
assert_eq!(h.pattern, "SOLID");
}
/// "?" lists the patterns and asks again, as AutoCAD does.
#[test]
fn lisp_hatch_question_mark_lists_patterns_and_asks_again() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"?\")").unwrap();
assert!(s.log.iter().any(|l| l.contains("Available patterns") && l.contains("ANSI31")), "{:?}", s.log);
assert!(s.prompt_text().contains("Enter a pattern name"), "{}", s.prompt_text());
for answer in ["ansi31", "", "", "_l", ""] {
s.cmdline(answer).unwrap();
}
assert_eq!(only_hatch(&s).1.pattern, "ANSI31");
}
/// A zero, a negative number, NaN or text answers a scale or spacing question again, changing
/// nothing; the answers after it are read as the values they are, and nothing panics.
#[test]
fn a_refused_hatch_scale_or_spacing_changes_nothing() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"ansi31\" \"0\" \"-5\" \"nan\" \"x\" 2 30 \"_l\" \"\")").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!(h.pattern, "ANSI31");
assert!((h.scale - 2.0).abs() < 1e-9, "{}", h.scale);
assert!((h.angle - 30f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert!(s.log.iter().any(|l| l.contains("Value must be positive and nonzero.")), "{:?}", s.log);
// A spacing refused and then cancelled leaves no hatch behind.
let before = hatch_count(&s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 \"0\")").unwrap();
assert!(s.running.is_some(), "still asking for the spacing");
assert!(s.prompt_text().contains("spacing"), "{}", s.prompt_text());
s.cancel();
assert_eq!(hatch_count(&s), before);
}
#[test]
fn user_hatch_spacing_at_the_limit_is_refused_and_just_above_it_draws_and_saves() {
let limit = MIN_HATCH_PATTERN_SCALE;
let spacing = limit.next_up();
let mut s = Session::new();
lisp_rectangle(&mut s);
s.execute("setvar", &json!({ "name": "HPSPACE", "value": spacing })).unwrap();
for value in [limit / 2.0, limit] {
let result = s.execute("setvar", &json!({ "name": "HPSPACE", "value": value }));
assert!(result.unwrap_err().to_string().contains("greater than"));
}
s.cmdline("(command \"_.hatch\" \"_u\" 0)").unwrap();
for value in [limit / 2.0, limit] {
s.cmdline(&value.to_string()).unwrap();
assert!(s.prompt_text().contains("Specify a spacing"), "{}", s.prompt_text());
}
assert!(s.log.iter().any(|line| line.contains("Hatch spacing must be greater than")), "{:?}", s.log);
let default = s.current_prompt().unwrap().default.unwrap().parse::<f64>().unwrap();
assert_eq!(default, spacing);
assert_eq!(crate::sysvars::get(&s, "HPSPACE"), Some(json!(spacing)));
for answer in ["", "_n", "_l", ""] {
s.cmdline(answer).unwrap();
}
// Draw a strip with room for a few lines so the sweep stays within its line budget.
let opts = cadcraft_render::Options { view: Some(Bounds2::from_points([Vec2::ZERO, Vec2::new(1.0, spacing * 5.0)])), ..Default::default() };
let original = s.doc().unwrap();
let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(original).as_bytes()).unwrap();
for drawing in [original, &reopened] {
let hatch = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap();
let display = cadcraft_render::build(drawing, &Space::Model, &opts);
let lines: Vec<_> = display
.prims
.iter()
.filter(|p| p.handle == hatch.handle && p.kind == cadcraft_render::Kind::Polyline)
.map(|p| display.points(p)[0].y)
.collect();
assert!(lines.len() >= 2, "expected multiple hatch lines, got {lines:?}");
for pair in lines.windows(2) {
let measured = (pair[1] - pair[0]).abs();
assert!((measured / spacing - 1.0).abs() < 1e-12, "drawn spacing {measured}, requested {spacing}");
}
}
}
/// A script's own HATCH line is not a routine's call: it keeps the interface's prompts and picks
/// the boundary first, as it did before a routine's answers were published.
#[test]
fn a_script_hatch_keeps_the_interface_prompts() {
let mut s = Session::new();
s.script("pline 0,0 4000,0 4000,2000 0,2000 c\nhatch\n").unwrap();
// The boundary question comes first: no pattern, scale or angle is asked.
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cmdline("2000,1000").unwrap();
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!((h.pattern.as_str(), h.scale), ("ANSI31", 1.0));
}
/// A routine's `(command …)` inside a script is still a routine's call: it takes the published
/// order, though the script's own HATCH line above does not.
#[test]
fn a_lisp_hatch_call_from_a_script_takes_the_published_order() {
let mut s = Session::new();
s.script("pline 0,0 4000,0 4000,2000 0,2000 c\n(command \"_.hatch\" \"dots\" 50 0 \"_l\" \"\")\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let h = only_hatch(&s).1;
assert_eq!(h.pattern, "DOTS");
assert!((h.scale - 50.0).abs() < 1e-9, "{}", h.scale);
}
/// A script that a routine starts with `(command "_.script" …)` runs its lines as a script: its
/// HATCH line takes the interface's options (A for the angle), not the routine's order.
#[test]
fn a_script_a_routine_starts_keeps_the_interface_prompts() {
let dir = std::env::temp_dir().join(format!("cadcraft-hatch-script-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("angle.scr");
std::fs::write(&file, "hatch A 45\n\n").unwrap();
let mut s = Session::new();
let path = file.to_string_lossy().replace('\\', "/");
s.cmdline(&format!("(command \"_.script\" \"{path}\")")).unwrap();
let a = s.doc().unwrap().header.f64("HPANG", 0.0);
let _ = std::fs::remove_dir_all(&dir);
assert!((a - std::f64::consts::FRAC_PI_4).abs() < 1e-9, "HPANG {a}; {}", s.prompt_text());
assert!(!s.lisp_program_input(), "the routine's flag is restored after the script");
}
/// -HATCH keeps its own questions, a routine's included: it picks the boundary first, and the
/// Properties option takes the pattern, scale and angle as before.
#[test]
fn dash_hatch_keeps_its_pick_boundary_prompts() {
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.cmdline("(command \"_.-hatch\")").unwrap();
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cancel();
// Typed by a person (the interface's dialog off) it is the same command line.
s.start("hatch").unwrap();
assert!(s.prompt_text().contains("Pick internal point"), "{}", s.prompt_text());
s.cancel();
}
/// A user-defined hatch is saved as one (pattern `_USER`, pattern type 0, its double flag) and
/// read back with its angle, spacing and families.
#[test]
fn a_user_defined_hatch_survives_a_dxf_save_and_read() {
let mut s = Session::new();
lisp_rectangle(&mut s);
s.cmdline("(command \"_.hatch\" \"_u\" 45 100 \"_y\" \"_l\" \"\")").unwrap();
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
let h = d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap();
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!(!h.solid);
assert!((h.scale - 100.0).abs() < 1e-9, "{}", h.scale);
assert!((h.angle - 45f64.to_radians()).abs() < 1e-12, "{}", h.angle);
assert_eq!(h.pattern_lines.len(), 2, "the doubled families are made again");
}
#[test] #[test]
fn unknown_pattern_error_and_catalog_name_the_pat_file_route() { fn unknown_pattern_error_and_catalog_name_the_pat_file_route() {
let mut s = Session::new(); let mut s = Session::new();
+58
View File
@@ -602,3 +602,61 @@ fn plot_path_extension_picks_the_format_like_export() {
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree"); assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
std::fs::remove_dir_all(&dir).ok(); 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);
}
+4 -4
View File
@@ -50,8 +50,8 @@ fn source(p: &Value) -> Result<(String, String)> {
} }
/// The result of a blocking LISP run as JSON, with the lines it printed. /// The result of a blocking LISP run as JSON, with the lines it printed.
fn report(s: &Session, from_log: u64, r: Option<std::result::Result<Lv, String>>) -> Value { fn report(s: &Session, from_log: usize, r: Option<std::result::Result<Lv, String>>) -> Value {
let output: Vec<String> = s.log_since(from_log).to_vec(); let output: Vec<String> = s.log.get(from_log..).map(|l| l.to_vec()).unwrap_or_default();
match r { match r {
Some(Ok(v)) => json!({ "value": to_text(&v, true), "output": output }), Some(Ok(v)) => json!({ "value": to_text(&v, true), "output": output }),
Some(Err(e)) => json!({ "error": e, "output": output }), Some(Err(e)) => json!({ "error": e, "output": output }),
@@ -62,7 +62,7 @@ fn report(s: &Session, from_log: u64, r: Option<std::result::Result<Lv, String>>
fn run_appload(s: &mut Session, p: &Value) -> Result<Value> { fn run_appload(s: &mut Session, p: &Value) -> Result<Value> {
let (name, text) = source(p)?; let (name, text) = source(p)?;
let before = s.lisp_commands(); let before = s.lisp_commands();
let from = s.log_mark(); let from = s.log.len();
let r = s.lisp_load(&name, &text, true)?; let r = s.lisp_load(&name, &text, true)?;
let mut out = report(s, from, r); let mut out = report(s, from, r);
// The commands the file defined, so a caller can run them next (a failed file may still // The commands the file defined, so a caller can run them next (a failed file may still
@@ -82,7 +82,7 @@ fn input_value(v: &Value) -> Lv {
fn run_lisp(s: &mut Session, p: &Value) -> Result<Value> { fn run_lisp(s: &mut Session, p: &Value) -> Result<Value> {
let code = str_param(p, "code").ok_or_else(|| bad("lisp", "`code` is required"))?; let code = str_param(p, "code").ok_or_else(|| bad("lisp", "`code` is required"))?;
let inputs = p.get("inputs").and_then(Value::as_array).map(|a| a.iter().map(input_value).collect()).unwrap_or_default(); let inputs = p.get("inputs").and_then(Value::as_array).map(|a| a.iter().map(input_value).collect()).unwrap_or_default();
let from = s.log_mark(); let from = s.log.len();
let r = s.lisp_eval(code, false, true, inputs).map_err(|e| match e { let r = s.lisp_eval(code, false, true, inputs).map_err(|e| match e {
EngineError::Other(m) => bad("lisp", m), EngineError::Other(m) => bad("lisp", m),
e => e, e => e,
+20 -80
View File
@@ -11,7 +11,6 @@ use cadcraft_geom::{Bounds2, Line, Vec2, line_line, point_in_polygon};
use serde_json::{Value, json}; use serde_json::{Value, json};
use super::offset::offset_points; use super::offset::offset_points;
use super::trim::ON_CUT;
use super::{Edges, trim}; use super::{Edges, trim};
use crate::cmd::helpers::lwpoly; use crate::cmd::helpers::lwpoly;
use crate::cmd::{CommandSpec, bad, point_param, targets}; use crate::cmd::{CommandSpec, bad, point_param, targets};
@@ -23,7 +22,7 @@ const MAX_FENCE: usize = 10_000;
const MAX_OBJECTS: usize = 10_000; const MAX_OBJECTS: usize = 10_000;
/// Most stretches one call removes (an object can lose several). /// Most stretches one call removes (an object can lose several).
const MAX_STRETCHES: usize = 10_000; const MAX_STRETCHES: usize = 10_000;
/// Most parts the preview draws (beyond that it shows nothing, to keep the cursor smooth). /// Most objects the preview draws (beyond that it shows nothing, to keep the cursor smooth).
const MAX_PREVIEW: usize = 2000; const MAX_PREVIEW: usize = 2000;
/// The traced line's distance from the edge, as a fraction of the edge's size. /// The traced line's distance from the edge, as a fraction of the edge's size.
const TRACE_GAP: f64 = 1e-5; const TRACE_GAP: f64 = 1e-5;
@@ -31,7 +30,7 @@ const TRACE_GAP: f64 = 1e-5;
pub(super) fn spec() -> CommandSpec { pub(super) fn spec() -> CommandSpec {
CommandSpec::new("extrim", "Extended Trim", run_extrim) CommandSpec::new("extrim", "Extended Trim", run_extrim)
.menu(&["Tools", "Additional Tools", "Extended Trim"]) .menu(&["Tools", "Additional Tools", "Extended Trim"])
.params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut, partly (of uncut, those cut in part)}") .params("{edge: hex (line, arc, circle, ellipse, polyline or spline), side: [x,y] (inside or outside a closed edge, an arc's circle or an elliptical arc's ellipse; one side of an open edge)} → trimmed, handles, skipped: {locked, other, uncut}")
.interactive(|s| Ok(Box::new(ExtrimM::new(s)))) .interactive(|s| Ok(Box::new(ExtrimM::new(s))))
} }
@@ -147,11 +146,6 @@ struct Edge {
impl Edge { impl Edge {
/// The cutting edge `h`: a line, arc, circle, ellipse, polyline or spline of the current space. /// The cutting edge `h`: a line, arc, circle, ellipse, polyline or spline of the current space.
/// Whether the edge is still an object of the space being edited (MSPACE and PSPACE change
/// it while EXTRIM runs): only there can TRIM cut with it.
fn in_space(&self, s: &Session) -> bool {
s.doc().is_ok_and(|d| d.space_of(self.handle).as_ref() == Some(&s.space()))
}
fn new(s: &Session, h: Handle) -> Result<Edge> { fn new(s: &Session, h: Handle) -> Result<Edge> {
let d = s.doc()?; let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| bad("extrim", format!("no object {}", h.hex())))?; let e = d.entity(h).ok_or_else(|| bad("extrim", format!("no object {}", h.hex())))?;
@@ -400,16 +394,14 @@ fn stretches_of(pts: &[Vec2], closed: bool, edge: &Grid, trace: &Grid) -> Option
} }
/// The trim of everything crossing `edge` on `side`, worked out without changing anything. /// The trim of everything crossing `edge` on `side`, worked out without changing anything.
/// `frozen`: the layers the active layout viewport freezes, whose objects it doesn't draw and fn plan(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Result<Plan> {
/// so leaves alone, as a selection through it does.
fn plan(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &Edge, side: Side) -> Result<Plan> {
let trace = edge.trace(side); let trace = edge.trace(side);
let trace_grid = Grid::new(&trace); let trace_grid = Grid::new(&trace);
let edge_grid = Grid::new(&edge.pts); let edge_grid = Grid::new(&edge.pts);
let tol = edge.gap / 20.0; let tol = edge.gap / 20.0;
let mut p = Plan::default(); let mut p = Plan::default();
let mut stretches_total = 0; let mut stretches_total = 0;
for h in crate::select::select_fence_in(d, space, frozen, &trace) { for h in crate::select::select_fence(d, space, &trace) {
if h == edge.handle { if h == edge.handle {
continue; continue;
} }
@@ -470,23 +462,6 @@ fn midpoint(pts: &[Vec2]) -> Option<Vec2> {
pts.last().copied() pts.last().copied()
} }
/// Whether `e` has no length at all: every point of its outline the same f64 point.
fn degenerate(d: &Drawing, e: &Entity, tol: f64) -> bool {
length(d, e, tol) <= 0.0
}
/// Whether TRIM would pass over a cut at `st`'s end (within ON_CUT of its pick) and run on to the
/// next one, taking more than `st`: such a stretch is left, by the trim and by its preview. The
/// ends and the pick lie on the outline traced within `tol` (and the pick is then brought onto
/// the object), so a true cut can be up to 3 `tol` nearer than the end found: that is the margin.
/// TRIM measures along the object, and so does this: the pick is the middle of the stretch's
/// longest part, half of that part from the nearer of its ends along the outline (straight across,
/// a folded polyline can bring an end next to the pick however far away it is along it).
fn too_short(st: &Stretch, tol: f64) -> bool {
let longest = st.parts.iter().map(|p| arc_length(p)).fold(0.0, f64::max);
longest / 2.0 <= ON_CUT + 3.0 * tol
}
/// The length of an object's drawn outline. /// The length of an object's drawn outline.
fn length(d: &Drawing, e: &Entity, tol: f64) -> f64 { fn length(d: &Drawing, e: &Entity, tol: f64) -> f64 {
crate::select::hit_polylines(d, e, tol).iter().flat_map(|pl| pl.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?)))).sum() crate::select::hit_polylines(d, e, tol).iter().flat_map(|pl| pl.windows(2).filter_map(|w| Some(w.first()?.dist(*w.get(1)?)))).sum()
@@ -513,15 +488,11 @@ pub(super) fn run_extrim(s: &mut Session, p: &Value) -> Result<Value> {
/// Trim every object crossing `edge` on `side`: one undo step, everything checked first. /// Trim every object crossing `edge` on `side`: one undo step, everything checked first.
fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> { fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
if !edge.in_space(s) {
return Err(bad("extrim", "the cutting edge is not in the space being edited; pick it again there"));
}
let space = s.space(); let space = s.space();
let plan = plan(s.doc()?, &space, s.viewport_frozen(), edge, side)?; let plan = plan(s.doc()?, &space, edge, side)?;
let edges = Edges { only: Some(std::slice::from_ref(&edge.handle)), implied: false }; let edges = Edges { only: Some(std::slice::from_ref(&edge.handle)), implied: false };
let tol = edge.gap / 20.0; let tol = edge.gap / 20.0;
let mut trimmed = 0; let mut trimmed = 0;
let mut partly = 0;
let mut created = Vec::new(); let mut created = Vec::new();
// Objects some planned cut failed on, reported rather than counted as done. // Objects some planned cut failed on, reported rather than counted as done.
let mut uncut = plan.uncut; let mut uncut = plan.uncut;
@@ -530,16 +501,7 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
let mut cut = false; let mut cut = false;
// The object as it is before any cut: its lines and arcs, exactly. // The object as it is before any cut: its lines and arcs, exactly.
let exact = s.doc()?.entity(h).and_then(|e| exact_outline(&e.kind)); let exact = s.doc()?.entity(h).and_then(|e| exact_outline(&e.kind));
for st in stretches { for x in stretches.into_iter().map(|st| st.pick) {
// TRIM passes over a cut within ON_CUT of the pick and runs on to the next one, which
// would take more than this stretch: a stretch that short is left, and said so.
if too_short(&st, tol) {
if !uncut.contains(&h) {
uncut.push(h);
}
continue;
}
let x = st.pick;
// The pick lies on the flattened outline, which strays from a large-radius arc by up to // The pick lies on the flattened outline, which strays from a large-radius arc by up to
// a millionth of its radius (far more than `tol` next to a short edge): bring it onto // a millionth of its radius (far more than `tol` next to a short edge): bring it onto
// the object itself, and measure the pieces exactly too. // the object itself, and measure the pieces exactly too.
@@ -578,10 +540,9 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
cut = true; cut = true;
live.retain(|l| *l != t); live.retain(|l| *l != t);
for n in pieces { for n in pieces {
// Never leave a piece of no length behind; a short one that has length stays, as // Never leave a piece of no length behind.
// TRIM leaves it.
let d = s.doc()?; let d = s.doc()?;
if d.entity(n).is_some_and(|e| degenerate(d, e, tol)) { if d.entity(n).is_some_and(|e| length(d, e, tol) <= tol) {
s.doc_mut()?.remove_entity(n); s.doc_mut()?.remove_entity(n);
} else { } else {
live.push(n); live.push(n);
@@ -589,12 +550,7 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
} }
} }
if cut { if cut {
// A partly cut object is counted once, with those not cut everywhere. trimmed += 1;
if uncut.contains(&h) {
partly += 1;
} else {
trimmed += 1;
}
created.extend(live.into_iter().filter(|l| *l != h)); created.extend(live.into_iter().filter(|l| *l != h));
} }
} }
@@ -606,13 +562,12 @@ fn trim_side(s: &mut Session, edge: &Edge, side: Side) -> Result<Value> {
message.push_str(&format!(" {} that can't be trimmed (blocks, hatches, text…) left as they are.", plan.other)); message.push_str(&format!(" {} that can't be trimmed (blocks, hatches, text…) left as they are.", plan.other));
} }
if !uncut.is_empty() { if !uncut.is_empty() {
message.push_str(&format!(" {} could not be cut everywhere the edge crosses them", uncut.len())); message.push_str(&format!(" {} could not be cut everywhere the edge crosses them.", uncut.len()));
message.push_str(&if partly > 0 { format!(" ({partly} of them cut in part).") } else { ".".to_string() });
} }
Ok(json!({ Ok(json!({
"trimmed": trimmed, "trimmed": trimmed,
"handles": created.iter().map(|h| h.hex()).collect::<Vec<_>>(), "handles": created.iter().map(|h| h.hex()).collect::<Vec<_>>(),
"skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len(), "partly": partly }, "skipped": { "locked": plan.locked, "other": plan.other, "uncut": uncut.len() },
"message": message, "message": message,
})) }))
} }
@@ -640,19 +595,15 @@ fn on_outline(segs: &[cadcraft_geom::Segment], p: Vec2) -> Vec2 {
} }
/// The parts the trim would remove, drawn red. /// The parts the trim would remove, drawn red.
fn preview(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &Edge, side: Side) -> Vec<Entity> { fn preview(d: &Drawing, space: &cadcraft_doc::Space, edge: &Edge, side: Side) -> Vec<Entity> {
let Ok(plan) = plan(d, space, frozen, edge, side) else { return Vec::new() }; let Ok(plan) = plan(d, space, edge, side) else { return Vec::new() };
let tol = edge.gap / 20.0; if plan.work.len() > MAX_PREVIEW {
// What costs is what is drawn: an object can lose many stretches, each of several parts.
let parts: usize =
plan.work.iter().flat_map(|(_, st)| st).filter(|st| !too_short(st, tol)).map(|st| st.parts.iter().filter(|p| p.len() >= 2).count()).sum();
if parts > MAX_PREVIEW {
return Vec::new(); return Vec::new();
} }
let mut out = Vec::new(); let mut out = Vec::new();
for (h, stretches) in plan.work { for (h, stretches) in plan.work {
let Some(e) = d.entity(h) else { continue }; let Some(e) = d.entity(h) else { continue };
for part in stretches.into_iter().filter(|st| !too_short(st, tol)).flat_map(|st| st.parts).filter(|p| p.len() >= 2) { for part in stretches.into_iter().flat_map(|st| st.parts).filter(|p| p.len() >= 2) {
let mut ent = Entity::new(Handle(0), lwpoly(part.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false)); let mut ent = Entity::new(Handle(0), lwpoly(part.into_iter().map(cadcraft_geom::PolyVertex::new).collect(), false));
ent.common.color = Color::Index(1); ent.common.color = Color::Index(1);
ent.common.layer = e.common.layer.clone(); ent.common.layer = e.common.layer.clone();
@@ -664,15 +615,10 @@ fn preview(d: &Drawing, space: &cadcraft_doc::Space, frozen: &[String], edge: &E
/// EXTRIM at the prompts: the cutting edge (or the one object selected beforehand), then the side, /// EXTRIM at the prompts: the cutting edge (or the one object selected beforehand), then the side,
/// with the parts that will go shown red as the cursor moves. /// with the parts that will go shown red as the cursor moves.
/// What a cached EXTRIM preview was worked out for: the space being edited and the frozen layers.
type PreviewFor = (cadcraft_doc::Space, Vec<String>);
pub(super) struct ExtrimM { pub(super) struct ExtrimM {
edge: Option<Edge>, edge: Option<Edge>,
/// The preview for each side (left, right), worked out once for the space being edited and the /// The preview for each side (left, right), worked out once.
/// layers the active viewport freezes then: a VPLAYER or MSPACE run meanwhile changes what the previews: RefCell<[Option<Vec<Entity>>; 2]>,
/// trim works on.
previews: RefCell<[Option<(PreviewFor, Vec<Entity>)>; 2]>,
} }
impl ExtrimM { impl ExtrimM {
@@ -747,22 +693,16 @@ impl Interactive for ExtrimM {
} }
fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec<Entity> { fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec<Entity> {
let Some(edge) = &self.edge else { return Vec::new() }; let Some(edge) = &self.edge else { return Vec::new() };
// An edge left in another space cuts nothing here, so nothing is shown going.
if !edge.in_space(s) {
return Vec::new();
}
let Some(side) = edge.side(cursor) else { return Vec::new() }; let Some(side) = edge.side(cursor) else { return Vec::new() };
let slot = usize::from(side == Side::Right); let slot = usize::from(side == Side::Right);
let (space, frozen) = (s.space(), s.viewport_frozen()); let cached = self.previews.borrow().get(slot).cloned().flatten();
let cached =
self.previews.borrow().get(slot).cloned().flatten().filter(|((sp, f), _)| *sp == space && f.as_slice() == frozen).map(|(_, v)| v);
let mut v = match cached { let mut v = match cached {
Some(v) => v, Some(v) => v,
None => { None => {
let Ok(d) = s.doc() else { return Vec::new() }; let Ok(d) = s.doc() else { return Vec::new() };
let v = preview(d, &space, frozen, edge, side); let v = preview(d, &s.space(), edge, side);
if let Some(c) = self.previews.borrow_mut().get_mut(slot) { if let Some(c) = self.previews.borrow_mut().get_mut(slot) {
*c = Some(((space.clone(), frozen.to_vec()), v.clone())); *c = Some(v.clone());
} }
v v
} }
+3 -19
View File
@@ -49,9 +49,9 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
// its first piece under the object's handle and the others under new ones, so only the first // its first piece under the object's handle and the others under new ones, so only the first
// stays one of the picked edges, as in a run of trims on the drawing itself. // stays one of the picked edges, as in a run of trims on the drawing itself.
let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h)); let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h));
let mut visit = |e: &Entity| { for e in store.iter() {
if !d.is_visible(e) { if !d.is_visible(e) {
return; continue;
} }
match overlay.get(&e.handle) { match overlay.get(&e.handle) {
Some(pieces) => { Some(pieces) => {
@@ -64,22 +64,6 @@ pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, ove
None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind), None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind),
None => {} None => {}
} }
};
match edges.only {
// Only the given edges: look them up rather than scan the whole space for them. A piece
// of one is keyed by its handle in the overlay, and the other pieces are never edges.
Some(es) => {
let mut seen = std::collections::HashSet::new();
for e in es.iter().filter(|h| seen.insert(**h) && store.contains(**h)).filter_map(|h| d.entity(*h)) {
visit(e);
}
}
// Every object is an edge (Quick mode, run on every preview): walk the space as it is.
None => {
for e in store.iter() {
visit(e);
}
}
} }
Ok(out) Ok(out)
} }
@@ -408,7 +392,7 @@ const MAX_SELF_CROSSINGS: usize = 1 << 16;
/// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within /// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within
/// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further, /// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further,
/// to 1e-6; on a line, further still, to 5e-4 on one 10 long). /// to 1e-6; on a line, further still, to 5e-4 on one 10 long).
pub(crate) const ON_CUT: f64 = 5e-7; const ON_CUT: f64 = 5e-7;
/// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick, /// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick,
/// so Quick mode leaves it in place rather than erasing it as one no edge crosses. /// so Quick mode leaves it in place rather than erasing it as one no edge crosses.
+31 -5
View File
@@ -240,8 +240,34 @@ fn tolerance(sp: &Spline, tol: f64) -> Result<Spline> {
// ---------------- control points ---------------- // ---------------- control points ----------------
/// The number of distinct control points: control points that wrap round repeat their first
/// `degree` at the end, and a clamped closed spline repeats its first at the end.
fn distinct(sp: &Spline) -> usize {
let n = sp.control.len();
if sp.wraps() {
n.saturating_sub(sp.degree)
} else if sp.closed && n > 2 && sp.control.first().zip(sp.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
n - 1
} else {
n
}
}
/// Indices holding distinct control point `j` (with its repeats).
fn copies(sp: &Spline, j: usize) -> Vec<usize> {
let (n, u) = (sp.control.len(), distinct(sp));
if j >= u {
return Vec::new();
}
let mut out = vec![j];
if u < n {
out.extend((j + u..n).step_by(u.max(1)));
}
out
}
fn move_control(sp: &Spline, j: usize, to: Vec2) -> Result<Spline> { fn move_control(sp: &Spline, j: usize, to: Vec2) -> Result<Spline> {
let ix = sp.control_copies(j); let ix = copies(sp, j);
if ix.is_empty() { if ix.is_empty() {
return Err(bad("splinedit", "control point index out of range")); return Err(bad("splinedit", "control point index out of range"));
} }
@@ -258,7 +284,7 @@ fn set_weight(sp: &Spline, j: usize, w: f64) -> Result<Spline> {
if !(w.is_finite() && w > 0.0) { if !(w.is_finite() && w > 0.0) {
return Err(other("Requires a positive weight.")); return Err(other("Requires a positive weight."));
} }
let ix = sp.control_copies(j); let ix = copies(sp, j);
if ix.is_empty() { if ix.is_empty() {
return Err(bad("splinedit", "control point index out of range")); return Err(bad("splinedit", "control point index out of range"));
} }
@@ -281,7 +307,7 @@ fn set_weight(sp: &Spline, j: usize, w: f64) -> Result<Spline> {
/// shape as far as it can. /// shape as far as it can.
fn delete_control(sp: &Spline, j: usize) -> Result<Spline> { fn delete_control(sp: &Spline, j: usize) -> Result<Spline> {
let p = sp.degree; let p = sp.degree;
let (n, u) = (sp.control.len(), sp.distinct_controls()); let (n, u) = (sp.control.len(), distinct(sp));
if j >= u { if j >= u {
return Err(bad("splinedit", "control point index out of range")); return Err(bad("splinedit", "control point index out of range"));
} }
@@ -452,7 +478,7 @@ impl SplineditM {
if fit { if fit {
sp.fit.clone() sp.fit.clone()
} else { } else {
let u = sp.distinct_controls(); let u = distinct(&sp);
sp.control.into_iter().take(u).collect() sp.control.into_iter().take(u).collect()
} }
} }
@@ -794,7 +820,7 @@ impl Interactive for SplineditM {
Sub::VertexOrder => self.input_order(s, &sp, &i)?, Sub::VertexOrder => self.input_order(s, &sp, &i)?,
Sub::VertexDelete => match point { Sub::VertexDelete => match point {
Some(p) => { Some(p) => {
let u = sp.distinct_controls(); let u = distinct(&sp);
let j = nearest(sp.control.get(..u).unwrap_or_default(), p).ok_or_else(|| other("The spline has no control points."))?; let j = nearest(sp.control.get(..u).unwrap_or_default(), p).ok_or_else(|| other("The spline has no control points."))?;
self.apply(s, json!({ "option": "vertexdelete", "index": j }))?; self.apply(s, json!({ "option": "vertexdelete", "index": j }))?;
} }
+12 -186
View File
@@ -1,6 +1,6 @@
//! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`. //! Paste tabular clipboard data (TSV from Excel or other spreadsheets) as a native `ACAD_TABLE`.
use cadcraft_doc::{CellStyle, EntityKind, Table, TableCell, TableStyle}; use cadcraft_doc::{EntityKind, Table, TableCell, TableStyle};
use cadcraft_geom::Vec2; use cadcraft_geom::Vec2;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -85,54 +85,33 @@ pub fn is_tsv_table(text: &str) -> bool {
} }
/// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly. /// Build an `ACAD_TABLE` entity from parsed cell strings, sizing columns and rows cleanly.
fn build_table(doc: &cadcraft_doc::Drawing, st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> Table { fn build_table(st: &TableStyle, at: Vec2, data: &[Vec<String>], text_height: Option<f64>) -> Table {
let cols = data.first().map_or(1, Vec::len).max(1); let cols = data.first().map_or(1, Vec::len).max(1);
let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 }); let th = text_height.unwrap_or_else(|| if st.text_height.is_finite() && st.text_height > 0.0 { st.text_height } else { 2.5 });
// Why: `cadcraft_render::table::layout` scales the resolved `Data` cell style's text height let margin = if st.text_height.is_finite() && st.text_height > 0.0 { st.margin * (th / st.text_height) } else { th * 0.5 };
// and horizontal/vertical margins by `th / st.text_height`, so sizing widths, wrap width, and
// row heights with the same scaled `Data` metrics keeps wrapped text inside custom-styled cells.
let scale = if st.text_height.is_finite() && st.text_height > 0.0 { th / st.text_height } else { 1.0 };
let data_cs = st.cell_style(CellStyle::DATA);
let cell_th = Some(data_cs.text_height * scale).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(th);
let margin_h = Some(data_cs.margin_h * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5);
let margin_v = Some(data_cs.margin_v * scale).filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(th * 0.5);
let mut col_chars = vec![1usize; cols]; let mut col_chars = vec![1usize; cols];
let mut row_heights = Vec::with_capacity(data.len());
let mut cells = Vec::with_capacity(data.len()); let mut cells = Vec::with_capacity(data.len());
for row in data { for row in data {
let mut max_lines = 1usize;
let mut table_row = Vec::with_capacity(cols); let mut table_row = Vec::with_capacity(cols);
for (c, raw) in row.iter().enumerate() { for (c, raw) in row.iter().enumerate() {
let line_count = raw.split('\n').count().clamp(1, 50);
max_lines = max_lines.max(line_count);
let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60); let max_chars = raw.split('\n').map(|line| line.chars().count()).max().unwrap_or(0).clamp(1, 60);
if let Some(slot) = col_chars.get_mut(c) { if let Some(slot) = col_chars.get_mut(c) {
*slot = (*slot).max(max_chars); *slot = (*slot).max(max_chars);
} }
table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() }); table_row.push(TableCell { text: cadcraft_doc::mtext_literal(raw), ..TableCell::default() });
} }
row_heights.push(th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin);
cells.push(table_row); cells.push(table_row);
} }
let min_col_w = (cell_th * 4.0 + 2.0 * margin_h).max(cell_th * 5.0); let min_col_w = (th * 4.0 + 2.0 * margin).max(th * 5.0);
let col_widths: Vec<f64> = let col_widths: Vec<f64> = col_chars.into_iter().map(|chars| (0.75 * th * chars as f64 + 2.0 * margin + 0.5 * th).max(min_col_w)).collect();
col_chars.into_iter().map(|chars| (0.95 * cell_th * chars as f64 + 2.0 * margin_h + 0.5 * cell_th).max(min_col_w)).collect();
let mut row_heights = Vec::with_capacity(cells.len());
for row in &cells {
let mut max_lines = 1usize;
for (c, cell) in row.iter().enumerate() {
if cell.text.is_empty() {
continue;
}
// Why: share the renderer's resolved MTEXT sizing inputs (named font, width_factor,
// oblique) so pasted row heights match how `cadcraft_render::table::draw` wraps cells.
let inner_w = col_widths.get(c).copied().unwrap_or(0.0) - 2.0 * margin_h;
let wrap_w = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 };
let mp = cadcraft_render::table_text_mtext_params(doc, &data_cs.text_style, Vec2::ZERO, cell_th, data_cs.align.clamp(1, 9), wrap_w);
let line_count = cadcraft_fonts::layout_mtext_with(&cell.text, &mp).lines.len().max(1);
max_lines = max_lines.max(line_count);
}
row_heights.push(cell_th * (max_lines as f64 * 5.0 / 3.0) + 2.0 * margin_v);
}
Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() } Table { insert: v3(at), col_widths, row_heights, cells, style: st.name.clone(), text_height: th, title: false, header: false, ..Table::default() }
} }
@@ -163,7 +142,7 @@ pub(super) fn run_pastetable(s: &mut Session, p: &Value) -> Result<Value> {
let rows = data.len(); let rows = data.len();
let cols = data.first().map_or(0, Vec::len); let cols = data.first().map_or(0, Vec::len);
let st = style_of(s); let st = style_of(s);
let table = build_table(s.doc()?, &st, at, &data, th); let table = build_table(&st, at, &data, th);
let h = s.add_entity(EntityKind::Table(table))?; let h = s.add_entity(EntityKind::Table(table))?;
s.set_selection(vec![h]); s.set_selection(vec![h]);
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols })) Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
@@ -228,16 +207,7 @@ impl Session {
let rows = data.len(); let rows = data.len();
let cols = data.first().map_or(0, Vec::len); let cols = data.first().map_or(0, Vec::len);
let st = style_of(self); let st = style_of(self);
let fallback; let table = build_table(&st, Vec2::ZERO, &data, text_height);
let doc = match self.doc() {
Ok(d) => d,
Err(_) => {
fallback = cadcraft_doc::Drawing::default();
&fallback
}
};
let table = build_table(doc, &st, Vec2::ZERO, &data, text_height);
self.last_paste_table = Some((tsv.to_string(), text_height));
let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled); let enabled = crate::find_command("pastetable").map_or((|_| Ok(())) as fn(&Session) -> std::result::Result<(), String>, |c| c.enabled);
self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols })) self.launch_interactive("pastetable", enabled, Box::new(PasteTableM { table, rows, cols }))
} }
@@ -331,148 +301,4 @@ mod tests {
assert_eq!(s.commands_started, before_started + 1); assert_eq!(s.commands_started, before_started + 1);
assert_eq!(s.last_command.as_deref(), Some("pastetable")); assert_eq!(s.last_command.as_deref(), Some("pastetable"));
} }
#[test]
fn long_wrapped_cells_cap_col_width_and_grow_row_height() {
let mut s = Session::new();
let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
assert!(long_cell.chars().count() > 60);
let tsv = format!("Short\t{long_cell}\n\"First line\n{long_cell}\"\t\nA\tB",);
let res = s.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0], "text_height": 2.0 })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
let EntityKind::Table(t) = &e.kind else { panic!("expected table") };
// Column 1 width is capped at 60 characters rather than growing unboundedly.
let st = style_of(&s);
let expected_cap_w = 0.95 * 2.0 * 60.0 + 2.0 * (st.margin * (2.0 / st.text_height)) + 0.5 * 2.0;
assert!((t.col_widths[1] - expected_cap_w).abs() < 1e-9);
// Row 0 wraps into multiple lines and is taller than single-line Row 2.
assert!(t.row_heights[0] > t.row_heights[2]);
// Row 1 combines a hard newline and a long wrapped line, making it taller than Row 0.
assert!(t.row_heights[1] > t.row_heights[0]);
}
#[test]
fn custom_data_cell_style_sizes_wrapped_rows_and_columns() {
let long_cell = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
let tsv = format!("Short\t{long_cell}\nA\tB");
let mut base = Session::new();
let r_base = base.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap();
let h_base = cadcraft_doc::Handle::parse_hex(r_base["handle"].as_str().unwrap()).unwrap();
let EntityKind::Table(t_base) = &base.doc().unwrap().entity(h_base).unwrap().kind else { panic!("expected table") };
let mut custom = Session::new();
{
let doc = custom.doc_mut().unwrap();
doc.text_styles.push(cadcraft_doc::TextStyle { name: "WideNotes".into(), width_factor: 1.8, ..cadcraft_doc::TextStyle::default() });
doc.table_styles.iter_mut().find(|ts| ts.name.eq_ignore_ascii_case("Standard")).unwrap().set_cell_style(CellStyle {
name: CellStyle::DATA.into(),
text_style: "WideNotes".into(),
text_height: 5.0,
margin_h: 4.0,
margin_v: 3.0,
..CellStyle::default()
});
}
let r_custom = custom.execute("pastetable", &json!({ "tsv": tsv, "at": [0, 0] })).unwrap();
let h_custom = cadcraft_doc::Handle::parse_hex(r_custom["handle"].as_str().unwrap()).unwrap();
let doc = custom.doc().unwrap();
let EntityKind::Table(t_custom) = &doc.entity(h_custom).unwrap().kind else { panic!("expected table") };
assert!(t_custom.col_widths[1] > t_base.col_widths[1]);
assert!(t_custom.row_heights[0] > t_base.row_heights[0]);
assert!(t_custom.row_heights[0] > t_custom.row_heights[1]);
let g = cadcraft_render::table_geometry(doc, t_custom);
let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap();
assert_eq!(tx.style, "WideNotes");
let laid = cadcraft_render::layout_table_text(doc, tx);
let default_laid = cadcraft_fonts::layout_mtext_with(
&tx.text,
&cadcraft_fonts::MTextParams { attach: tx.attach, width: tx.wrap_width, ..cadcraft_fonts::MTextParams::new(tx.at, tx.height) },
);
assert!(laid.lines.len() > default_laid.lines.len(), "wider text style must wrap into more lines");
assert!(t_custom.row_heights[0] >= laid.lines.len() as f64 * tx.height * 5.0 / 3.0 + 2.0 * 3.0 - 1e-6);
assert!(!laid.strokes.is_empty());
for s in &laid.strokes {
for p in s {
assert!(
p.y <= t_custom.insert.y + 1e-6 && p.y >= t_custom.insert.y - t_custom.row_heights[0] - 1e-6,
"rendered stroke spilled outside row 0 [{}..={}]: y={}",
t_custom.insert.y - t_custom.row_heights[0],
t_custom.insert.y,
p.y
);
}
}
}
#[test]
fn cell_wrapping_past_fifty_lines_is_not_clamped() {
let mut s = Session::new();
let long_cell = vec!["word"; 800].join(" ");
let res = s.execute("pastetable", &json!({ "tsv": format!("A\t{long_cell}\n1\t2"), "at": [0, 0], "text_height": 2.0 })).unwrap();
let h = cadcraft_doc::Handle::parse_hex(res["handle"].as_str().unwrap()).unwrap();
let doc = s.doc().unwrap();
let EntityKind::Table(t) = &doc.entity(h).unwrap().kind else { panic!("expected table") };
let g = cadcraft_render::table_geometry(doc, t);
let tx = g.texts.iter().find(|tx| tx.row == 0 && tx.col == 1).unwrap();
let laid = cadcraft_render::layout_table_text(doc, tx);
assert!(laid.lines.len() > 50, "expected >50 wrapped lines, got {}", laid.lines.len());
let st = style_of(&s);
let margin_v = st.margin * (2.0 / st.text_height);
let fifty_line_h = 2.0 * (50.0 * 5.0 / 3.0) + 2.0 * margin_v;
assert!(t.row_heights[0] > fifty_line_h);
assert!((t.row_heights[0] - (2.0 * (laid.lines.len() as f64 * 5.0 / 3.0) + 2.0 * margin_v)).abs() < 1e-9);
}
#[test]
fn enter_repeats_pastetable_with_last_payload() {
let mut s = Session::new();
s.start_paste_table("A\tB\n1\t2\n", Some(3.0)).unwrap();
s.input(Input::Point(Vec2::ZERO)).unwrap();
assert!(s.running.is_none());
s.input(Input::Enter).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("pastetable"));
s.input(Input::Point(Vec2::new(50.0, 0.0))).unwrap();
assert!(s.running.is_none());
let tables: Vec<_> = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Table(t) => Some(t),
_ => None,
})
.collect();
assert_eq!(tables.len(), 2);
assert_eq!(tables[0].cells, tables[1].cells);
assert_eq!(tables[0].text_height, 3.0);
assert_eq!(tables[1].text_height, 3.0);
assert_eq!(tables[0].insert.xy(), Vec2::ZERO);
assert_eq!(tables[1].insert.xy(), Vec2::new(50.0, 0.0));
}
#[test]
fn execute_pastetable_without_tsv_still_errors_and_other_command_overrides_repeat() {
let mut s = Session::new();
let err = s.execute("pastetable", &Value::Null).unwrap_err().to_string();
assert!(err.contains("`tsv` string is required"), "{err}");
s.start_paste_table("A\tB\n1\t2\n", None).unwrap();
s.input(Input::Point(Vec2::ZERO)).unwrap();
for t in ["line", "0,0", "10,0", ""] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
s.input(Input::Enter).unwrap();
assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("line"));
}
} }
+1 -3
View File
@@ -791,9 +791,7 @@ fn uncovered(d: &Drawing, e: &Entity, others: &[EntityKind], tol: f64) -> Vec<En
let mut ts: Vec<f64> = ends.iter().filter(|p| ab.closest(**p).dist(**p) <= near).map(|p| ab.param_of(*p).clamp(0.0, 1.0)).collect(); let mut ts: Vec<f64> = ends.iter().filter(|p| ab.closest(**p).dist(**p) <= near).map(|p| ab.param_of(*p).clamp(0.0, 1.0)).collect();
ts.extend([0.0, 1.0]); ts.extend([0.0, 1.0]);
ts.sort_by(f64::total_cmp); ts.sort_by(f64::total_cmp);
// Only cuts that are one point as far as f64 can tell: a tolerance in drawing units ts.dedup_by(|x, y| (*x - *y).abs() * len <= 1e-9 * (1.0 + a.len()));
// that grew with the distance from the origin merged real cuts far from it.
ts.dedup_by(|x, y| (*x - *y).abs() * len <= 64.0 * f64::EPSILON * (1.0 + a.len()));
for t in ts.windows(2) { for t in ts.windows(2) {
let (Some(&t0), Some(&t1)) = (t.first(), t.get(1)) else { continue }; let (Some(&t0), Some(&t1)) = (t.first(), t.get(1)) else { continue };
let (p, q) = (ab.at(t0), ab.at(t1)); let (p, q) = (ab.at(t0), ab.at(t1));
+5 -7
View File
@@ -7,7 +7,6 @@
/// Commands that read or write files, each path held to the roots where the file is touched. /// Commands that read or write files, each path held to the roots where the file is touched.
pub const FILES: &[&str] = &[ pub const FILES: &[&str] = &[
"-hatch",
"-linetype", "-linetype",
"-plottermanager", "-plottermanager",
"-wblock", "-wblock",
@@ -50,8 +49,6 @@ pub const FILES: &[&str] = &[
"publish", "publish",
"qsave", "qsave",
"recover", "recover",
"refclose",
"refedit",
"reinit", "reinit",
"saveas", "saveas",
"script", "script",
@@ -268,8 +265,9 @@ pub const NO_FILES: &[&str] = &[
"attdisp.normal", "attdisp.normal",
"attdisp.on", "attdisp.on",
"attdisp.off", "attdisp.off",
"refedit.levels", "refedit",
"refset", "refset",
"refclose",
"bedit", "bedit",
"bsave", "bsave",
"bsaveas", "bsaveas",
@@ -523,9 +521,9 @@ mod tests {
use std::collections::BTreeSet; use std::collections::BTreeSet;
/// Words in a command's parameter doc that usually name a file. In these commands they don't: /// 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, `refedit.levels` reports paths of nested /// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a
/// references, and `blocks.reference.grips` reports a direction. /// direction.
const NOT_FILES: &[&str] = &["array", "arraypath", "refedit.levels", "blocks.reference.grips"]; const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"];
/// The words of a command's documentation, lower case. /// The words of a command's documentation, lower case.
fn words(doc: &str) -> BTreeSet<String> { fn words(doc: &str) -> BTreeSet<String> {
+1 -8
View File
@@ -136,14 +136,7 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
EntityKind::Polyline3d(p) => set_xy(p.points.get_mut(index)?, to), EntityKind::Polyline3d(p) => set_xy(p.points.get_mut(index)?, to),
EntityKind::Spline(sp) => { EntityKind::Spline(sp) => {
if sp.fit.is_empty() { if sp.fit.is_empty() {
// A closed spline's repeats of the control vertex move with it (#3566). *sp.control.get_mut(index)? = to;
let copies = sp.control_copies(index);
if copies.is_empty() {
return None;
}
for i in copies {
*sp.control.get_mut(i)? = to;
}
} else { } else {
let mut fit = sp.fit.clone(); let mut fit = sp.fit.clone();
*fit.get_mut(index)? = to; *fit.get_mut(index)? = to;
-29
View File
@@ -249,32 +249,3 @@ fn grips_on_locked_layers_and_hostile_values() {
} }
} }
} }
/// #3566: a closed spline keeps some control vertices twice: SPLINE CV's Close repeats the first
/// at the end, and control vertices that wrap round repeat the first `degree`. Each control
/// vertex has one grip, and dragging it moves its copies, so the spline stays closed.
#[test]
fn a_closed_spline_has_one_grip_per_control_vertex_and_stays_closed() {
let mut s = Session::new();
let square = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)];
let clamped = h(&s.execute("spline.cv", &json!({"control": [[0, 0], [10, 0], [10, 10], [0, 10]], "closed": true})).unwrap());
let wraps = cadcraft_geom::Spline {
degree: 3,
knots: (0..11).map(f64::from).collect(),
control: square.iter().chain(&square[..3]).copied().collect(),
closed: true,
..Default::default()
};
assert!(wraps.wraps());
let wrapped = s.add_entity(EntityKind::Spline(wraps)).unwrap();
for sp in [clamped, wrapped] {
let g = s.grips_of(sp).unwrap();
let coincide = g.iter().enumerate().any(|(i, a)| g.iter().skip(i + 1).any(|b| a.near(*b, 1e-9)));
assert!(!coincide, "no grip lies on another: {g:?}");
s.grip_edit(sp, 0, v(-3.0, -3.0), GripMode::Stretch).unwrap();
let EntityKind::Spline(x) = kind(&s, sp) else { panic!() };
assert!(!x.control.iter().any(|c| near(*c, 0.0, 0.0)), "every copy moved: {:?}", x.control);
let (lo, hi) = x.domain();
assert!(x.eval(lo).near(x.eval(hi), 1e-9), "still closed: {:?} {:?}", x.eval(lo), x.eval(hi));
}
}
+2 -7
View File
@@ -3,15 +3,12 @@ use super::cmd;
/// Options and values the interactive commands remember for the rest of the session, offered as /// Options and values the interactive commands remember for the rest of the session, offered as
/// the `<default>` the next time they ask (as AutoCAD does). Values AutoCAD keeps in a drawing /// the `<default>` the next time they ask (as AutoCAD does). Values AutoCAD keeps in a drawing
/// system variable (HPNAME, OFFSETDIST, FILLETRAD, CHAMFERA, POLYSIDES…) live in the drawing /// system variable (HPNAME, OFFSETDIST, FILLETRAD, CHAMFERA, POLYSIDES…) live in the drawing
/// header instead. Drawing commands called with JSON use their own parameter defaults. /// header instead. JSON calls never read these: their explicit parameters and documented defaults
/// stay authoritative.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct LastUsed { pub struct LastUsed {
/// HATCH/GRADIENT starts at "Select objects" instead of "Pick internal point". /// HATCH/GRADIENT starts at "Select objects" instead of "Pick internal point".
pub hatch_select: bool, pub hatch_select: bool,
/// HPSPACE: line spacing for user-defined hatches.
pub hatch_spacing: f64,
/// HPDOUBLE: whether user-defined hatches have a second family of lines.
pub hatch_double: bool,
/// POLYGON: circumscribed about the circle (the `C` option) instead of inscribed. /// POLYGON: circumscribed about the circle (the `C` option) instead of inscribed.
pub polygon_circumscribed: bool, pub polygon_circumscribed: bool,
/// ROTATE angle (radians). /// ROTATE angle (radians).
@@ -38,8 +35,6 @@ impl Default for LastUsed {
fn default() -> Self { fn default() -> Self {
LastUsed { LastUsed {
hatch_select: false, hatch_select: false,
hatch_spacing: 1.0,
hatch_double: false,
polygon_circumscribed: false, polygon_circumscribed: false,
rotate_angle: 0.0, rotate_angle: 0.0,
scale_factor: 1.0, scale_factor: 1.0,
-23
View File
@@ -126,15 +126,8 @@ pub struct Session {
/// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it; /// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it;
/// it resumes when that command ends. One level, as in AutoCAD. /// it resumes when that command ends. One level, as in AutoCAD.
pub suspended: Option<Running>, pub suspended: Option<Running>,
/// The command history. It is trimmed from the front when it grows long, so to find the lines
/// echoed since some moment keep a [`Session::log_mark`], not an index into it.
pub log: Vec<String>, pub log: Vec<String>,
/// Lines [`Session::echo`] has added to `log`, trimmed and cleared ones included.
echoed: u64,
pub last_command: Option<String>, pub last_command: Option<String>,
/// Last TSV payload and optional text height passed to [`Session::start_paste_table`], so
/// pressing Enter to repeat `pastetable` restarts interactive placement.
pub(crate) last_paste_table: Option<(String, Option<f64>)>,
/// LASTPOINT. /// LASTPOINT.
pub last_point: Vec2, pub last_point: Vec2,
/// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract /// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract
@@ -233,9 +226,7 @@ impl Session {
program_input: false, program_input: false,
suspended: None, suspended: None,
log: Vec::new(), log: Vec::new(),
echoed: 0,
last_command: None, last_command: None,
last_paste_table: None,
last_point: Vec2::ZERO, last_point: Vec2::ZERO,
area: 0.0, area: 0.0,
perimeter: 0.0, perimeter: 0.0,
@@ -331,25 +322,11 @@ impl Session {
let m = msg.into(); let m = msg.into();
log::debug!("{m}"); log::debug!("{m}");
self.log.push(m); self.log.push(m);
self.echoed = self.echoed.saturating_add(1);
if self.log.len() > 5000 { if self.log.len() > 5000 {
self.log.drain(..1000); self.log.drain(..1000);
} }
} }
/// A mark in the command history: the number of lines echoed so far. Unlike an index into
/// `log`, it stays valid when the history is trimmed from the front or cleared.
pub fn log_mark(&self) -> u64 {
self.echoed
}
/// The lines echoed since `mark` ([`Session::log_mark`]) that the history still holds: all of
/// them, or the last ones when the history was trimmed past the first.
pub fn log_since(&self, mark: u64) -> &[String] {
let new = usize::try_from(self.echoed.saturating_sub(mark)).unwrap_or(usize::MAX);
self.log.get(self.log.len().saturating_sub(new)..).unwrap_or_default()
}
/// Common properties for new objects (CLAYER, CECOLOR, CELTYPE, CELWEIGHT, CELTSCALE). /// Common properties for new objects (CLAYER, CECOLOR, CELTYPE, CELWEIGHT, CELTSCALE).
pub fn current_common(&self) -> Common { pub fn current_common(&self) -> Common {
let Ok(d) = self.doc() else { return Common::default() }; let Ok(d) = self.doc() else { return Common::default() };
+3 -36
View File
@@ -170,14 +170,12 @@ pub(crate) struct Limits {
pub string_bytes: u64, pub string_bytes: u64,
/// Maximum interpreter steps per synchronous callback. /// Maximum interpreter steps per synchronous callback.
pub callback_steps: u64, pub callback_steps: u64,
/// Steps a routine run on without frames ([`Session::lisp_run_until_input`]) may take in all.
pub frameless_steps: u64,
} }
impl Default for Limits { impl Default for Limits {
/// Provide finite cons-cell, string-byte, synchronous-callback and step limits for a LISP run. /// Provide finite cons-cell, string-byte, and synchronous-callback limits for a LISP run.
fn default() -> Self { fn default() -> Self {
Limits { cells: value::MAX_CELLS, string_bytes: value::STRING_BUDGET, callback_steps: 500_000_000, frameless_steps: BLOCKING_CAP } Limits { cells: value::MAX_CELLS, string_bytes: value::STRING_BUDGET, callback_steps: 500_000_000 }
} }
} }
@@ -206,7 +204,7 @@ struct Run {
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with /// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`]. /// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool, answer: bool,
/// Steps taken, for the caps on blocking runs and on routines run on without frames. /// Steps taken, for the cap on blocking runs.
steps: u64, steps: u64,
/// The `*error*` handler is the one running. /// The `*error*` handler is the one running.
handler: bool, handler: bool,
@@ -365,28 +363,6 @@ impl Session {
self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield))) self.lisp.run.as_ref().is_some_and(|r| matches!(r.waiting, Some(Need::Yield)))
} }
/// Carry on a routine that gave the interface a frame ([`Session::lisp_busy`]) until it ends or
/// waits for input, where nothing else would: a script calls this before each input it gives,
/// which belongs to what the routine waits for or comes after it, and once it ends; a host
/// with no window calls it after each line it types. No one can stop the routine by hand
/// meanwhile, so past `limits.frameless_steps` steps, as many as a programmatic call may take,
/// it stops with the error such a call gets.
pub fn lisp_run_until_input(&mut self) {
while self.lisp_busy() {
let cap = self.lisp.limits.frameless_steps;
if self.lisp.run.as_ref().is_some_and(|r| r.steps > cap) {
// `*error*` gets the message and runs on the same count: an endless one stops at
// the next pass.
self.lisp_error(LispError::quit(format!("routine stopped after {cap} steps")));
continue;
}
if let Some(r) = self.lisp.run.as_mut() {
r.waiting = None;
}
self.lisp_drive();
}
}
/// Run the machine until it finishes or waits. /// Run the machine until it finishes or waits.
fn lisp_drive(&mut self) { fn lisp_drive(&mut self) {
loop { loop {
@@ -744,15 +720,6 @@ impl Session {
Some(label) Some(label)
} }
/// Why U may not take back the running routine's last step: it would undo a REFCLOSE Save
/// that already wrote an xref's file ([`crate::cmd::blocks::refedit::undo_barrier`]).
pub(crate) fn lisp_undo_barrier(&self) -> Option<String> {
let uid = self.routine_steps()?;
let st = self.docs.iter().find(|d| d.uid == uid)?;
let snap = self.lisp.steps.undo.back()?;
crate::cmd::blocks::refedit::undo_barrier(&st.doc, &snap.doc)
}
/// U or REDO inside the running routine went on to the drawing's steps before it: the /// U or REDO inside the running routine went on to the drawing's steps before it: the
/// routine's own undo step starts from the drawing as that left it, and REDO brings back that /// routine's own undo step starts from the drawing as that left it, and REDO brings back that
/// step before what U took back of the routine's. /// step before what U took back of the routine's.
-90
View File
@@ -908,48 +908,6 @@ fn appload_and_load() {
assert!(r["error"].as_str().is_some_and(|e| e.contains("bad argument type"))); assert!(r["error"].as_str().is_some_and(|e| e.contains("bad argument type")));
} }
/// Echo lines until the next one trims the command history from the front.
fn fill_history(s: &mut Session) {
// Grow it to its first trim, then back up to the length it had just before it.
let mut top = 0;
loop {
let len = s.log.len();
s.echo("filler");
if s.log.len() < len {
break;
}
top = s.log.len();
}
while s.log.len() < top {
s.echo("filler");
}
}
/// #3643: the `lisp` and `appload` JSON commands report the lines their run printed, also when
/// the command history is trimmed from the front while it runs.
#[test]
fn a_lisp_calls_output_survives_the_history_trim() {
let mut s = session();
// The `y` lines a reply reports; it reports nothing from before the call.
let ys = |r: &serde_json::Value| {
let out = r["output"].as_array().cloned().unwrap_or_default();
assert!(!out.contains(&serde_json::json!("filler")), "{r}");
out.iter().filter(|l| *l == "y").count()
};
let lines = |n: usize| format!("(repeat {n} (princ \"y\") (terpri))");
fill_history(&mut s);
let r = s.execute("lisp", &serde_json::json!({"code": lines(20)})).unwrap();
assert_eq!(ys(&r), 20, "{r}");
fill_history(&mut s);
let r = s.execute("appload", &serde_json::json!({"name": "ys.lsp", "text": lines(20)})).unwrap();
assert_eq!(ys(&r), 20, "{r}");
// A run that prints more than the history holds reports every line still held: all its own.
fill_history(&mut s);
let held = s.log.len();
let r = s.execute("lisp", &serde_json::json!({"code": lines(held + 100)})).unwrap();
assert_eq!(ys(&r), s.log.len(), "{r}");
}
/// `command` gives an entity name, alone or as `entsel` returns it (name and point), to a prompt /// `command` gives an entity name, alone or as `entsel` returns it (name and point), to a prompt
/// picking one object: the point picks that object, and a bare name stands at its DXF group 10 /// picking one object: the point picks that object, and a bare name stands at its DXF group 10
/// point. Each call and its numbers are AutoCAD 2024's (accoreconsole, read back with `entget`); /// point. Each call and its numbers are AutoCAD 2024's (accoreconsole, read back with `entget`);
@@ -1673,54 +1631,6 @@ fn an_expression_at_a_prompt_has_a_short_allowance() {
assert_eq!(circles(&s), 0); assert_eq!(circles(&s), 0);
} }
/// #3635: a script's next input goes to a routine an earlier input started only once that routine
/// has run on to its end or to the input it waits for: where there is no window, nothing else
/// carries on a routine that gave the interface a frame. Each loop here takes more than a slice.
#[test]
fn a_script_runs_a_long_routine_on_before_its_next_input() {
let mut s = session();
let circles = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Circle(_))).count();
let n = super::SLICE;
// CIRCLE's radius (a `pause`) and the `getint` answer come on the next lines, after a loop
// each; the last line's routine runs on before the script returns.
let script = format!(
"(progn (repeat {n} (setq x 1)) (command \"circle\" \"0,0\" pause) (setq k (getint \"Count: \")) (repeat {n} (setq x 2)))\n\
5\n\
42\n\
(setq after (list x k))\n\
(progn (repeat {n} (setq x 3)) (setq last x))\n"
);
s.script(&script).unwrap();
assert!(!s.lisp_running(), "{:?}", s.log);
assert_eq!(circles(&s), 1, "{:?}", s.log);
assert_eq!(ok(&mut s, "after"), "(2 42)");
assert_eq!(ok(&mut s, "last"), "3");
}
/// #3635: a routine a script runs on gets no frames, so nothing can stop it by hand: an endless
/// one is stopped with an error once it has taken the steps it may, an endless `*error*` handler
/// in turn, and the script goes on.
#[test]
fn a_script_stops_an_endless_routine() {
let mut s = session();
let slice = super::SLICE;
// How far an endless count gets with a cap of `cap` steps; the line after it still runs.
let count = |s: &mut Session, cap: u64| {
s.lisp.limits.frameless_steps = cap;
s.script("(setq i 0)\n(while T (setq i (1+ i)))\n(setq after i)\n").unwrap();
assert!(!s.lisp_running(), "{:?}", s.log);
ok(s, "after").parse::<i64>().unwrap()
};
// Stopped after its first slice, and after five: about five times as far, not unbounded.
let first = count(&mut s, 0);
let five = count(&mut s, 4 * slice);
assert!(first > 0 && five > 3 * first && five < 7 * first, "{first} {five}");
assert!(s.log.iter().any(|l| l.starts_with("; error: routine stopped after")), "{:?}", s.log);
s.script("(defun *error* (msg) (setq caught msg) (while T))\n(while T)\n").unwrap();
assert!(!s.lisp_running(), "the routine and its handler were stopped: {:?}", s.log);
assert!(ok(&mut s, "caught").contains("routine stopped after"));
}
/// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped /// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped
/// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor. /// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor.
#[test] #[test]
+1 -50
View File
@@ -437,7 +437,7 @@ impl Formatted {
out.push_str("\\P"); out.push_str("\\P");
} }
if *props != emitted { if *props != emitted {
out.push_str(&props.code_after(&emitted)); out.push_str(&props.code());
emitted = props.clone(); emitted = props.clone();
} }
let end = chars.iter().skip(i).position(|c| *c == '\n').map_or(chars.len(), |n| i + n); let end = chars.iter().skip(i).position(|c| *c == '\n').map_or(chars.len(), |n| i + n);
@@ -664,53 +664,4 @@ mod tests {
assert!(Formatted::fits(&format!("{}a{}", "{".repeat(64), "}".repeat(64)))); assert!(Formatted::fits(&format!("{}a{}", "{".repeat(64), "}".repeat(64))));
assert!(!Formatted::fits(&format!("{}a{}", "{".repeat(65), "}".repeat(65)))); assert!(!Formatted::fits(&format!("{}a{}", "{".repeat(65), "}".repeat(65))));
} }
#[test]
fn mixed_paragraph_line_spacing_reset_survives_textedit_roundtrip() {
let mut s = crate::Session::new();
let res = s
.execute(
"mtext",
&serde_json::json!({
"at": [0.0, 0.0],
"height": 0.2,
"text": "\\pxsm1.5;First\\P\\pxs*;Second\\PThird",
}),
)
.unwrap();
let handle = res["handle"].as_str().unwrap().to_string();
let doc_handle = cadcraft_doc::Handle::parse_hex(&handle).unwrap();
let orig_contents = match &s.doc().unwrap().entity(doc_handle).unwrap().kind {
cadcraft_doc::EntityKind::MText(m) => m.contents.clone(),
_ => panic!("expected MText"),
};
let mut f = Formatted::from_contents_with_height(&orig_contents, Some(0.2));
assert!(f.set_text("First\nSecond edited\nThird", &CharFmt::default()));
let edited = f.to_contents();
s.execute("textedit", &serde_json::json!({"handle": handle, "text": edited})).unwrap();
let saved_contents = match &s.doc().unwrap().entity(doc_handle).unwrap().kind {
cadcraft_doc::EntityKind::MText(m) => m.contents.clone(),
_ => panic!("expected MText"),
};
let reopened = Formatted::from_contents_with_height(&saved_contents, Some(0.2));
assert_eq!(reopened.para(0).line_spacing, Some(cadcraft_fonts::ParaLineSpacing::Multiple(1.5)), "{saved_contents}");
assert_eq!(reopened.para(1).line_spacing, None, "{saved_contents}");
assert_eq!(reopened.para(2).line_spacing, None, "{saved_contents}");
let p_08 = cadcraft_fonts::MTextParams {
line_spacing: 0.8,
line_spacing_exact: false,
..cadcraft_fonts::MTextParams::new(cadcraft_geom::Vec2::ZERO, 0.2)
};
let saved_layout = cadcraft_fonts::layout_mtext_with(&saved_contents, &p_08);
let all_15 = cadcraft_fonts::layout_mtext_with("\\pxsm1.5;First\\PSecond edited\\PThird", &p_08);
assert!(
saved_layout.bounds.height() < all_15.bounds.height() - 0.05,
"saved={:?} vs all_15={:?} ({saved_contents})",
saved_layout.bounds.height(),
all_15.bounds.height()
);
}
} }
+32 -7
View File
@@ -126,14 +126,36 @@ pub fn snap_name(m: u32) -> &'static str {
mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n) mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n)
} }
/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the /// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest /// first, then every other snap of the modes in `osmode` under the aperture (each endpoint of
/// first, then deferred snaps, then Nearest), without repeats. /// each object, each intersection …; [`crate::snap::osnap_all`]), best first, without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> { pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 { 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()) {
return Vec::new(); return Vec::new();
} }
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred) 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)) {
out.push(h);
}
}
out
} }
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with. /// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
@@ -343,12 +365,15 @@ impl Session {
Frame::Snap { mode } => { Frame::Snap { mode } => {
// Snap the point with this mode alone, within the aperture. // Snap the point with this mode alone, within the aperture.
let prompt = self.current_prompt(); let prompt = self.current_prompt();
let space = self.space(); let (doc, space, frozen) = {
let st = self.state()?;
(st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec())
};
let aperture = self.pixel_size() * self.settings.aperture.max(1.0); let aperture = self.pixel_size() * self.settings.aperture.max(1.0);
let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 }; let hatch = if self.settings.osnaphatch { mode::HATCH } else { 0 };
let base = prompt.as_ref().and_then(|q| q.base); let base = prompt.as_ref().and_then(|q| q.base);
let deferred = prompt.as_ref().is_some_and(|q| q.deferred); let deferred = prompt.as_ref().is_some_and(|q| q.deferred);
let hit = crate::snap::osnap(self.doc()?, &space, p, aperture, mode | hatch, base, deferred); let hit = crate::snap::osnap_with_frozen(&doc, &space, p, aperture, mode | hatch, base, deferred, &frozen);
match hit { match hit {
Some(h) if self.point_mods.is_empty() => return self.input_snapped(h), Some(h) if self.point_mods.is_empty() => return self.input_snapped(h),
Some(h) => p = h.point, Some(h) => p = h.point,
+3 -2
View File
@@ -76,8 +76,9 @@ pub struct Prompt {
/// Rubber-band origin (for direct distance entry, ortho and polar). /// Rubber-band origin (for direct distance entry, ortho and polar).
pub base: Option<Vec2>, pub base: Option<Vec2>,
/// The command resolves deferred tangent/perpendicular snaps ([`Input::Deferred`]) at this /// 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). Elsewhere a deferred /// prompt (a point with no base yet, e.g. the first point of a line; with a base, only
/// pick arrives as the plain point it was picked at. /// tangents, e.g. a circle's radius). Elsewhere a deferred pick arrives as the plain point it
/// was picked at.
pub deferred: bool, pub deferred: bool,
/// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit /// The base is a rectangle's first corner (ZOOM Window, PLOTWINDOW, RECTANG, ARRAYRECT's unit
/// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area. /// cell, MTEXT): ortho does not bend the opposite corner, so the rectangle keeps its area.
+26 -131
View File
@@ -1,6 +1,6 @@
//! Hit testing and window/crossing selection. //! Hit testing and window/crossing selection.
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, ViewportBounds, entity_bounds}; use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds};
use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon}; use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
use crate::spatial::{self, SpatialIndex}; use crate::spatial::{self, SpatialIndex};
@@ -13,19 +13,8 @@ fn draws_a_block(e: &Entity) -> bool {
/// Polylines approximating an entity for hit testing, tessellated at `tol`. /// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> { pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
hit_polylines_in(d, e, &mut ViewportBounds::new(&[]), tol, true)
}
/// [`hit_polylines`] through the layout viewport `view`: the parts of a block reference on the
/// layers frozen in that viewport are not drawn there, so they are not hit, and the box around a
/// dimension or multileader is the box around the parts that are drawn ([`bounds_in`]). A
/// dimension's definition points stay, as [`ViewportBounds`] says. With `room` the rectangle a
/// dimension is hit along keeps the room of the text the viewport leaves out ([`outline_in`]), as
/// a selection that touches the dimension tests it; without, it is the box of what the viewport
/// draws, as a selection that must hold the dimension tests it.
fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, tol: f64, room: bool) -> Vec<Vec<Vec2>> {
if matches!(e.kind, EntityKind::Insert(_)) { if matches!(e.kind, EntityKind::Insert(_)) {
let list = insert_geometry(d, e, tol, view.frozen()); let list = insert_geometry(d, e, tol);
return list return list
.prims .prims
.iter() .iter()
@@ -68,21 +57,19 @@ fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a
{ {
// Text-like objects are hit inside their box; a dimension kept as read that draws its // Text-like objects are hit inside their box; a dimension kept as read that draws its
// block, like a dimension. // block, like a dimension.
let b = bounds_in(d, e, None, view); let b = entity_bounds(d, e, 0);
if b.is_empty() { if b.is_empty() {
return Vec::new(); return Vec::new();
} }
let c = b.corners(); let c = b.corners();
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]]; let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) { if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::MLeader(_)) || draws_a_block(e) {
let list = cadcraft_render::build_entities_in_viewport( let list = cadcraft_render::build_entities(
d, d,
std::iter::once(e), std::iter::once(e),
&cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() }, &cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() },
view.frozen(),
); );
v = list.prims.iter().map(|p| list.points(p).to_vec()).collect(); v = list.prims.iter().map(|p| list.points(p).to_vec()).collect();
let c = if room { outline_in(d, e, view, b) } else { b }.corners();
v.push(vec![c[0], c[1], c[2], c[3], c[0]]); v.push(vec![c[0], c[1], c[2], c[3], c[0]]);
} }
v v
@@ -135,46 +122,8 @@ fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a
} }
} }
/// The rectangle a selection through the layout viewport `view` hits `e` along, where `b` is the fn insert_geometry(d: &Drawing, e: &Entity, tol: f64) -> cadcraft_render::DisplayList {
/// box of what that viewport draws of it ([`bounds_in`]): `b`, and for a dimension drawn from a cadcraft_render::build_entities(d, std::iter::once(e), &cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() })
/// block also the room of the text in that block that the viewport leaves out
/// ([`ViewportBounds::leaves_out`]) and the drawing itself shows. Without the text the box ends at
/// the dimension line, so a side of the rectangle would run through the place of the text, and a
/// crossing window there, which touched nothing while the rectangle held the text, would take the
/// dimension by that side. Text the drawing hides (its own invisible flag, a layer frozen for the
/// whole drawing or turned off) had no room in the rectangle before a viewport was counted, and
/// has none here. A selection that only has to touch the dimension tests this rectangle, its box
/// test first included ([`touch_box_in`]). A window and a window polygon still need only what the
/// viewport draws inside them ([`in_window_in`], [`select_polygon_in`]).
fn outline_in(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, b: Bounds2) -> Bounds2 {
let EntityKind::Dimension(dm) = &e.kind else { return b };
if view.frozen().is_empty() {
return b;
}
let Some(blk) = dm.block.as_ref().and_then(|n| d.block(n)) else { return b };
let at = dm.insertion_point.xy();
let shown = |part: &Entity| part.common.visible && d.layer(&part.common.layer).is_none_or(|l| !l.frozen && l.on);
let mut out = b;
for part in
blk.entities.iter().filter(|part| matches!(part.kind, EntityKind::Text(_) | EntityKind::MText(_)) && view.leaves_out(part) && shown(part))
{
let t = entity_bounds(d, part, 0);
if !t.is_empty() {
out = out.union(&Bounds2::from_points([t.min + at, t.max + at]));
}
}
out
}
/// What the layout viewport that freezes the layers in `frozen` draws of the block reference `e`
/// (none frozen: what the drawing shows), for hit testing at `tol`.
fn insert_geometry(d: &Drawing, e: &Entity, tol: f64, frozen: &[String]) -> cadcraft_render::DisplayList {
cadcraft_render::build_entities_in_viewport(
d,
std::iter::once(e),
&cadcraft_render::Options { tolerance: tol, linetypes: false, ..Default::default() },
frozen,
)
} }
/// The part of an image its clips leave showing, as triangles (three points each); empty when a /// The part of an image its clips leave showing, as triangles (three points each); empty when a
@@ -192,10 +141,8 @@ fn shown_image_tris(img: &cadcraft_render::DImage) -> Vec<Vec2> {
tris tris
} }
/// Whether a fill or an image of the block reference `e` reaches into the box `bx`, of what the fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64) -> bool {
/// layout viewport that freezes the layers in `frozen` draws of it ([`insert_geometry`]). let list = insert_geometry(d, e, tol);
fn insert_fill_hits_box(d: &Drawing, e: &Entity, bx: &Bounds2, tol: f64, frozen: &[String]) -> bool {
let list = insert_geometry(d, e, tol, frozen);
list.prims.iter().any(|p| { list.prims.iter().any(|p| {
if let cadcraft_render::Kind::Image { index } = p.kind { if let cadcraft_render::Kind::Image { index } = p.kind {
let Some(img) = list.images.get(index as usize) else { return false }; let Some(img) = list.images.get(index as usize) else { return false };
@@ -222,17 +169,11 @@ fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
/// Distance from `p` to the entity (0 inside text boxes and solid fills). /// Distance from `p` to the entity (0 inside text boxes and solid fills).
pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
entity_distance_in(d, e, &mut ViewportBounds::new(&[]), p, tol) let polys = hit_polylines(d, e, tol);
}
/// [`entity_distance`] through the layout viewport `view`: to what that viewport draws of the
/// entity ([`hit_polylines_in`]).
fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, p: Vec2, tol: f64) -> f64 {
let polys = hit_polylines_in(d, e, view, tol, true);
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min); let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_)) let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_))
|| matches!(e.kind, EntityKind::Tolerance(_)); || matches!(e.kind, EntityKind::Tolerance(_));
if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, view, p) { if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) {
best = 0.0; best = 0.0;
} }
// A solid hatch fills its loops with odd parity under its island style, as it is drawn, not // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not
@@ -253,10 +194,8 @@ fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<
/// Whether `p` is on the text of a dimension or multileader: inside the box around its words, /// Whether `p` is on the text of a dimension or multileader: inside the box around its words,
/// turned with the text, as plain text is hit anywhere inside its box. Their other geometry is /// turned with the text, as plain text is hit anywhere inside its box. Their other geometry is
/// hit along its lines, so without this the cursor found the object only between the letters' /// hit along its lines, so without this the cursor found the object only between the letters'
/// edges and the lines. Text in a dimension's block that `view` leaves out /// edges and the lines.
/// ([`ViewportBounds::leaves_out`]) does not count: the viewport does not draw text on a layer fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool {
/// frozen in it, and a pick in its box finds nothing there, as in AutoCAD.
fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool {
match &e.kind { match &e.kind {
// A dimension with a block (as AutoCAD saves them) is drawn from that block: its text is // A dimension with a block (as AutoCAD saves them) is drawn from that block: its text is
// the text there, not the text the dimension's own geometry would place. // the text there, not the text the dimension's own geometry would place.
@@ -264,7 +203,7 @@ fn in_text(d: &Drawing, e: &Entity, view: &ViewportBounds<'_>, p: Vec2) -> bool
// The block draws translated by the insertion point (group 12): test there (#2634). // The block draws translated by the insertion point (group 12): test there (#2634).
Some(blk) => { Some(blk) => {
let p = p - dm.insertion_point.xy(); let p = p - dm.insertion_point.xy();
blk.entities.iter().filter(|be| !view.leaves_out(be)).any(|be| match &be.kind { blk.entities.iter().any(|be| match &be.kind {
EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p), EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p),
EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p), EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p),
_ => false, _ => false,
@@ -441,26 +380,6 @@ pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor:
pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 { pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Bounds2 {
known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0))) known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0)))
} }
/// The box a selection made through the layout viewport `view` tests `e` against: the box of
/// what that viewport draws of it. `known` is the box the spatial index holds, of what the
/// drawing shows; it stands unless the viewport freezes layers and `e` draws a block (a block
/// reference, a dimension, a multileader), whose contents on those layers the viewport leaves
/// out. That box is never larger than `known`, so the index still finds every candidate. The
/// frame of blank text stays in it, as in [`bounds_of`].
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &mut ViewportBounds<'a>) -> Bounds2 {
let from_a_block = matches!(e.kind, EntityKind::Insert(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_));
if from_a_block && !view.frozen().is_empty() { pick_bounds(d, e, view.entity_bounds(d, e)) } else { bounds_of(d, e, known) }
}
/// The box a selection through `view` that only has to touch `e` (a pick, a crossing window, a
/// fence, a crossing polygon) tests before its hit geometry: [`bounds_in`] with the room
/// [`outline_in`] keeps, so a side of the rectangle a dimension is hit along that lies in that
/// room is not passed over. A selection that must hold `e` tests [`bounds_in`] itself.
fn touch_box_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &mut ViewportBounds<'a>) -> Bounds2 {
let b = bounds_in(d, e, known, view);
outline_in(d, e, view, b)
}
pub(crate) fn is_infinite(e: &Entity) -> bool { pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
} }
@@ -537,13 +456,10 @@ pub(crate) fn pick_scanning(
) -> Option<Handle> { ) -> Option<Handle> {
let probe = Bounds2::new(p, p).expand(aperture); let probe = Bounds2::new(p, p).expand(aperture);
let query = probe.expand(aperture); let query = probe.expand(aperture);
// One viewport's boxes serve every candidate, from whichever of the readings below asks.
let view = std::cell::RefCell::new(ViewportBounds::new(frozen));
let hit = |e: &Entity, known: Option<Bounds2>| { let hit = |e: &Entity, known: Option<Bounds2>| {
let view = &mut *view.borrow_mut();
selectable(d, e, frozen) selectable(d, e, frozen)
&& (is_infinite(e) || touch_box_in(d, e, known, view).expand(aperture).intersects(&probe)) && (is_infinite(e) || bounds_of(d, e, known).expand(aperture).intersects(&probe))
&& entity_distance_in(d, e, view, p, aperture / 4.0) <= aperture && entity_distance(d, e, p, aperture / 4.0) <= aperture
}; };
// Candidates come topmost first: the first within the aperture is the one. // Candidates come topmost first: the first within the aperture is the one.
let topmost = |ix: &SpatialIndex, cands: Vec<u32>, below: u32| { let topmost = |ix: &SpatialIndex, cands: Vec<u32>, below: u32| {
@@ -590,13 +506,9 @@ pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, apert
let ix = spatial::index(d, space); let ix = spatial::index(d, space);
let probe = Bounds2::new(p, p).expand(aperture); let probe = Bounds2::new(p, p).expand(aperture);
let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() }; let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() };
let mut view = ViewportBounds::new(frozen);
cands cands
.filter(|(e, known)| { .filter(|(e, known)| selectable(d, e, frozen) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe)))
selectable(d, e, frozen) .filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture)
&& (is_infinite(e) || touch_box_in(d, e, *known, &mut view).expand(aperture).intersects(&probe))
&& entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture
})
.map(|(e, _)| e.handle) .map(|(e, _)| e.handle)
.collect() .collect()
} }
@@ -643,8 +555,7 @@ pub(crate) fn select_window_with(
) -> Vec<Handle> { ) -> Vec<Handle> {
let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() }; let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() };
let tol = window_tol(&bx); let tol = window_tol(&bx);
let mut view = ViewportBounds::new(frozen); cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window_in(d, e, *known, &mut view, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
} }
/// The tessellation tolerance window and crossing tests use for a box. /// The tessellation tolerance window and crossing tests use for a box.
@@ -655,29 +566,15 @@ pub(crate) fn window_tol(bx: &Bounds2) -> f64 {
/// Whether a window box (`crossing` false: entirely inside) or a crossing box (inside or /// Whether a window box (`crossing` false: entirely inside) or a crossing box (inside or
/// touching its geometry, not just its bounding box) selects `e`. /// touching its geometry, not just its bounding box) selects `e`.
pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bounds2, crossing: bool, tol: f64) -> bool { pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bounds2, crossing: bool, tol: f64) -> bool {
in_window_in(d, e, known, &mut ViewportBounds::new(&[]), bx, crossing, tol)
}
/// [`in_window`] through the layout viewport `view`: a block reference is inside the box, or
/// touches it, by the parts that viewport draws ([`bounds_in`], [`hit_polylines_in`]).
fn in_window_in<'a>(
d: &'a Drawing,
e: &Entity,
known: Option<Bounds2>,
view: &mut ViewportBounds<'a>,
bx: &Bounds2,
crossing: bool,
tol: f64,
) -> bool {
let infinite = is_infinite(e); let infinite = is_infinite(e);
let eb = bounds_in(d, e, known, view); let eb = bounds_of(d, e, known);
if !infinite && bx.contains_box(&eb) { if !infinite && bx.contains_box(&eb) {
return true; return true;
} }
if !crossing || (!infinite && !outline_in(d, e, view, eb).intersects(bx)) { if !crossing || (!infinite && !eb.intersects(bx)) {
return false; return false;
} }
let polys = hit_polylines_in(d, e, view, tol, true); let polys = hit_polylines(d, e, tol);
let hit = polys.iter().any(|pl| { let hit = polys.iter().any(|pl| {
if pl.len() == 1 { if pl.len() == 1 {
pl.first().is_some_and(|p| bx.contains(*p)) pl.first().is_some_and(|p| bx.contains(*p))
@@ -688,7 +585,7 @@ fn in_window_in<'a>(
// A crossing box inside a text bounding rectangle selects the text. // A crossing box inside a text bounding rectangle selects the text.
if hit if hit
|| (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_))) || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_)))
|| (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol, view.frozen())) || (matches!(e.kind, EntityKind::Insert(_)) && insert_fill_hits_box(d, e, bx, tol))
{ {
return true; return true;
} }
@@ -732,14 +629,13 @@ pub(crate) fn select_fence_with(
let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0; let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0;
let probe = fb.expand(tol); let probe = fb.expand(tol);
let Some(cands) = candidates(d, space, ix, &probe, true, false) else { return Vec::new() }; let Some(cands) = candidates(d, space, ix, &probe, true, false) else { return Vec::new() };
let mut view = ViewportBounds::new(frozen);
let mut out = Vec::new(); let mut out = Vec::new();
for (e, known) in cands { for (e, known) in cands {
// Infinite objects have no useful bounds; like window selection, test their geometry directly. // Infinite objects have no useful bounds; like window selection, test their geometry directly.
if !selectable(d, e, frozen) || (!is_infinite(e) && !touch_box_in(d, e, known, &mut view).intersects(&probe)) { if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
continue; continue;
} }
let polys = hit_polylines_in(d, e, &mut view, tol, true); let polys = hit_polylines(d, e, tol);
let hit = fence.windows(2).any(|f| { let hit = fence.windows(2).any(|f| {
let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false }; let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false };
let fl = Line::new(*a, *b); let fl = Line::new(*a, *b);
@@ -770,18 +666,17 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
let Some(cands) = candidates(d, space, &ix, &pb, crossing, false) else { return Vec::new() }; let Some(cands) = candidates(d, space, &ix, &pb, crossing, false) else { return Vec::new() };
let edges: Vec<Line> = let edges: Vec<Line> =
poly.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?))).chain(poly.last().map(|l| Line::new(*l, *first))).collect(); poly.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?))).chain(poly.last().map(|l| Line::new(*l, *first))).collect();
let mut view = ViewportBounds::new(frozen);
let mut out = Vec::new(); let mut out = Vec::new();
for (e, known) in cands { for (e, known) in cands {
let infinite = is_infinite(e); let infinite = is_infinite(e);
if !selectable(d, e, frozen) || (infinite && !crossing) { if !selectable(d, e, frozen) || (infinite && !crossing) {
continue; continue;
} }
let eb = if crossing { touch_box_in(d, e, known, &mut view) } else { bounds_in(d, e, known, &mut view) }; let eb = bounds_of(d, e, known);
if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } { if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } {
continue; continue;
} }
let polys = hit_polylines_in(d, e, &mut view, tol, crossing); let polys = hit_polylines(d, e, tol);
let crosses = polys.iter().any(|pl| { let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| { pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some())) w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
+28 -119
View File
@@ -16,21 +16,6 @@ impl Session {
self.input_line(t, false) self.input_line(t, false)
} }
/// Whether Space with `typed` on the command line types a space instead of submitting: at a
/// free-text prompt, or inside an unclosed parenthesised LISP expression where the command
/// line evaluates one.
pub fn space_is_text(&self, typed: &str) -> bool {
if self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number) {
return true;
}
let accepts_lisp = match self.current_prompt() {
None => self.lisp_prompt().is_none(),
Some(p) => !p.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo(),
};
let rest = if self.running.is_none() { typed.trim_start() } else { typed };
accepts_lisp && matches!(lisp_token_end(rest), Some(None))
}
/// One line of input: each space ends an input and an empty input (two spaces in a row, a /// One line of input: each space ends an input and an empty input (two spaces in a row, a
/// trailing space, an empty line) is Enter, which at `Command:` repeats the last command. In a /// trailing space, an empty line) is Enter, which at `Command:` repeats the last command. In a
/// script, a free-text prompt (TEXT/MTEXT contents) takes the rest of the line, a prompt with /// script, a free-text prompt (TEXT/MTEXT contents) takes the rest of the line, a prompt with
@@ -40,11 +25,6 @@ impl Session {
let mut rest = line; let mut rest = line;
let mut first = true; let mut first = true;
loop { loop {
// A script's next input goes to what the routine an earlier one started waits for, or
// comes after that routine: carry it on first, as the window's frames would.
if script {
self.lisp_run_until_input();
}
if self.running.is_none() { if self.running.is_none() {
if !script && !first { if !script && !first {
return Ok(()); return Ok(());
@@ -207,14 +187,7 @@ impl Session {
return Err(EngineError::BadParams { cmd: "script".into(), msg: "a script is already running; nested scripts are not supported".into() }); return Err(EngineError::BadParams { cmd: "script".into(), msg: "a script is already running; nested scripts are not supported".into() });
} }
self.in_script = true; self.in_script = true;
// A script that a LISP routine started (`(command "_.script" …)`) feeds its own lines: they
// are not the routine's input, so a command they start answers as from a script.
let program_input = std::mem::replace(&mut self.program_input, false);
let r = self.script_lines(text); let r = self.script_lines(text);
self.program_input = program_input;
// The routine the last input started or answered runs on too: with no window, nothing
// would carry it on once the script returns.
self.lisp_run_until_input();
self.in_script = false; self.in_script = false;
r r
} }
@@ -240,105 +213,41 @@ fn lisp_expression(t: &str) -> bool {
} }
/// The next command-line input in `rest` and what follows it: up to a space or tab, except that /// The next command-line input in `rest` and what follows it: up to a space or tab, except that
/// a LISP expression runs to its closing parenthesis (spaces, quoted strings and comments /// a LISP expression runs to its closing parenthesis (spaces and quoted strings inside it).
/// inside it).
fn next_token(rest: &str) -> (&str, Option<&str>) { fn next_token(rest: &str) -> (&str, Option<&str>) {
match lisp_token_end(rest) {
Some(Some(end)) => {
// As after any input, a space ends it and a trailing one is Enter.
let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m));
(&rest[..end], more)
}
// Unbalanced: all of it (the reader reports the error).
Some(None) => (rest, None),
None => match rest.split_once([' ', '\t']) {
Some((tok, more)) => (tok, Some(more)),
None => (rest, None),
},
}
}
/// For `rest` starting a parenthesised LISP form (`(…` or `!(…`), the byte offset past its
/// matching `)`, or `Some(None)` while it is still open; `None` when `rest` is not one.
fn lisp_token_end(rest: &str) -> Option<Option<usize>> {
let lead = rest.len() - rest.trim_start_matches('!').len(); let lead = rest.len() - rest.trim_start_matches('!').len();
let body = rest.get(lead..)?; if rest.get(lead..).is_some_and(|r| r.starts_with('(')) {
if !body.starts_with('(') { let (mut depth, mut in_str, mut escaped) = (0i32, false, false);
return None; for (i, c) in rest.char_indices().skip(lead) {
} if in_str {
let mut depth = 0i32; match (escaped, c) {
let mut in_str = false; (true, _) => escaped = false,
let mut chars = body.char_indices().peekable(); (false, '\\') => escaped = true,
while let Some((i, c)) = chars.next() { (false, '"') => in_str = false,
if in_str { _ => {}
}
continue;
}
match c { match c {
'\\' => { '"' => in_str = true,
chars.next(); '(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
let end = i + 1;
// As after any input, a space ends it and a trailing one is Enter.
let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m));
return (&rest[..end], more);
}
} }
'"' => in_str = false,
_ => {} _ => {}
} }
continue;
}
match c {
';' if chars.peek().is_some_and(|(_, n)| *n == '|') => {
chars.next();
while let Some((_, bc)) = chars.next() {
if bc == '|' && chars.peek().is_some_and(|(_, n)| *n == ';') {
chars.next();
break;
}
}
}
';' => {
for (_, lc) in chars.by_ref() {
if lc == '\n' {
break;
}
}
}
'"' => in_str = true,
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(Some(lead + i + 1));
}
}
_ => {}
} }
// Unbalanced: all of it (the reader reports the error).
return (rest, None);
} }
Some(None) match rest.split_once([' ', '\t']) {
} Some((tok, more)) => (tok, Some(more)),
None => (rest, None),
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn open_lisp_forms_treat_space_as_text_only_where_lisp_evaluates() {
let mut s = Session::new();
assert!(s.space_is_text("(+ 1"));
assert!(s.space_is_text(" (+ 1"));
assert!(s.space_is_text("!(+ 1"));
assert!(s.space_is_text("(princ \"a ) b\""));
assert!(s.space_is_text("(princ ;| ) |; 1"));
assert!(s.space_is_text("(+ 1 ; )"));
assert!(!s.space_is_text("(+ 1 ; )\n 2)"));
assert!(!s.space_is_text("(+ 1 2)"));
assert!(!s.space_is_text("!x"));
assert!(!s.space_is_text("line"));
assert_eq!(next_token("(+ 1 ;| ) |; 2) rest"), ("(+ 1 ;| ) |; 2)", Some("rest")));
assert_eq!(next_token("(+ 1 ; )\n 2) rest"), ("(+ 1 ; )\n 2)", Some("rest")));
s.cmdline("circle").unwrap();
assert!(s.space_is_text("(list 1"));
assert!(!s.space_is_text("(list 1 2)"));
s.cancel();
// Prompts inside a waiting LISP routine (`getpoint`) do not evaluate LISP expressions.
s.cmdline("(getpoint)").unwrap();
assert!(!s.space_is_text("(+ 1"));
s.cancel();
} }
} }
-7
View File
@@ -104,17 +104,10 @@ impl Session {
/// Take the last step back. Inside a LISP routine, the routine's last command first; past /// Take the last step back. Inside a LISP routine, the routine's last command first; past
/// those, the drawing's step before the routine, which then starts from there. /// those, the drawing's step before the routine, which then starts from there.
pub fn undo(&mut self) -> Result<Option<String>> { pub fn undo(&mut self) -> Result<Option<String>> {
// A REFCLOSE Save that wrote an xref's file stops U inside a routine as it does outside.
if let Some(why) = self.lisp_undo_barrier() {
return Err(EngineError::Other(why));
}
if let Some(label) = self.lisp_take_back(false) { if let Some(label) = self.lisp_take_back(false) {
return Ok(Some(label)); return Ok(Some(label));
} }
let st = self.state_mut()?; 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 Some(snap) = st.undo.pop() else { return Ok(None) };
let cur = st.swap_in(snap); let cur = st.swap_in(snap);
let label = cur.label.clone(); let label = cur.label.clone();
-16
View File
@@ -78,15 +78,6 @@ impl Session {
self.command_origin self.command_origin
} }
/// Whether an AutoLISP routine is feeding the command line now: the `(command …)` call it makes,
/// or the token it types into a command that is already running. A script's own lines are the
/// program's input too ([`Session::start`] records [`Origin::Program`] for them), so this tells a
/// routine's call from a script's line, and a routine's call inside a script is this, not the
/// script's.
pub fn lisp_program_input(&self) -> bool {
self.program_input
}
/// Start a command by name or alias as if typed at the command line. A script's commands are /// Start a command by name or alias as if typed at the command line. A script's commands are
/// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so /// the program's ([`Origin::Program`]), as those of [`Session::start_programmatic`] are, and so
/// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command /// is a command started by a token a LISP routine feeds through [`Session::typed`]: `(command
@@ -242,13 +233,6 @@ impl Session {
if input == Input::Enter if input == Input::Enter
&& let Some(last) = self.last_command.clone() && let Some(last) = self.last_command.clone()
{ {
// Why: `pastetable` has no standalone `interactive` factory because its TSV
// payload comes from the clipboard; repeat it with the last pasted payload.
if last == "pastetable"
&& let Some((tsv, th)) = self.last_paste_table.clone()
{
return self.start_paste_table(&tsv, th);
}
return self.start(&last); return self.start(&last);
} }
return Ok(()); return Ok(());
+553 -210
View File
@@ -65,6 +65,24 @@ pub struct SnapHit {
} }
impl 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. /// The command input a pick at this snap gives: a deferred snap or a plain point.
pub fn input(&self) -> crate::Input { pub fn input(&self) -> crate::Input {
match self.deferred { match self.deferred {
@@ -72,33 +90,6 @@ impl SnapHit {
None => crate::Input::Point(self.point), None => crate::Input::Point(self.point),
} }
} }
fn plain(mode: u32, point: Vec2) -> SnapHit {
SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None }
}
/// Where this hit sorts among the candidates near a cursor: specific snaps by distance
/// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest.
fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) {
let class = if self.deferred.is_some() {
1
} else if self.mode == mode::NEA {
2
} else {
0
};
(class, snap_score(self.mode, self.point, cursor, aperture))
}
/// The same snap as `o`: mode and point, from the same source (paper 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.
fn same(&self, o: &SnapHit) -> bool {
self.mode == o.mode
&& self.deferred.is_some() == o.deferred.is_some()
&& self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport)
&& self.point.near(o.point, 1e-9 * (1.0 + self.point.len()))
}
} }
/// The curve a deferred snap refers to. /// The curve a deferred snap refers to.
@@ -137,12 +128,16 @@ impl SnapCurve {
} }
/// Points on the curve whose perpendicular passes through `p`; `picked` is where the curve /// 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). /// was picked, kept when `p` is the center of a circle or arc (every radius is perpendicular).
fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> { pub(crate) fn perpendiculars(&self, p: Vec2, picked: Vec2) -> Vec<Vec2> {
match self { match self {
SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => { SnapCurve::Circle { center, radius } | SnapCurve::Arc { center, radius, .. } => {
let u = (p - *center).normalized(); let u = (p - *center).normalized();
if u == Vec2::ZERO { if u == Vec2::ZERO {
vec![Circle::new(*center, *radius).closest(picked)] // 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),
}]
} else { } else {
[*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect() [*center + u * *radius, *center - u * *radius].into_iter().filter(|q| self.contains(*q)).collect()
} }
@@ -229,23 +224,34 @@ fn prim_segments(p: &Prim) -> Vec<Segment> {
/// Tangent and perpendicular snaps need the base point (the other end of the line). With no /// 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`), /// 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 /// they snap as *deferred*: the hit carries the curve and is resolved once the other end is
/// known. Deferred hits only win where no other snap does (they are as unspecific as Nearest). /// 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).
pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Option<SnapHit> { 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 { if osmode == 0 || osmode & mode::OFF != 0 {
return None; return None;
} }
let ix = crate::spatial::index(d, space); let ix = crate::spatial::index(d, space);
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred) osnap_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred, frozen).0
}
/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest
/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest.
/// Snaps seen through layout viewports are included.
pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
let ix = crate::spatial::index(d, space);
osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0
} }
#[cfg(test)]
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with( pub(crate) fn osnap_with(
d: &Drawing, d: &Drawing,
@@ -257,7 +263,7 @@ pub(crate) fn osnap_with(
base: Option<Vec2>, base: Option<Vec2>,
deferred: bool, deferred: bool,
) -> Option<SnapHit> { ) -> 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. /// Find the best object snap and retain the local-space primitives gathered for that query.
@@ -271,40 +277,21 @@ pub(crate) fn osnap_with_neighborhood(
osmode: u32, osmode: u32,
base: Option<Vec2>, base: Option<Vec2>,
deferred: bool, deferred: bool,
frozen: &[String],
) -> (Option<SnapHit>, Option<Vec<Prim>>) { ) -> (Option<SnapHit>, Option<Vec<Prim>>) {
let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred);
(all.into_iter().next(), prims)
}
/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered.
#[allow(clippy::too_many_arguments)]
fn osnap_all_with_neighborhood(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
cursor: Vec2,
aperture: f64,
osmode: u32,
base: Option<Vec2>,
deferred: bool,
) -> (Vec<SnapHit>, Option<Vec<Prim>>) {
if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) { if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) {
return (Vec::new(), None); return (None, None);
} }
let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) { let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, None) {
Some((hits, prims)) => (hits, Some(prims)), Some((hit, prims)) => (hit, Some(prims)),
None => (Vec::new(), None), None => (None, None),
}; };
let views = viewport::near(d, space, cursor, aperture); let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() { if views.is_empty() {
return (all, near_prims); return (best.map(|(h, _)| h), near_prims);
} }
let model = Space::Model; let model = Space::Model;
let model_ix = crate::spatial::index(d, &model); let model_ix = crate::spatial::index(d, &model);
// What a click picks across spaces stays as it was: each space's best snap, and a viewport's
// replaces the best so far only when it scores closer. A paper-space Nearest can therefore
// beat an Endpoint seen through a viewport, which `ranked` alone would put first.
let mut pick = all.first().copied();
for view in views { for view in views {
let model_cursor = view.to_model(cursor); let model_cursor = view.to_model(cursor);
let model_aperture = aperture / view.scale; let model_aperture = aperture / view.scale;
@@ -312,66 +299,49 @@ fn osnap_all_with_neighborhood(
if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) { if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) {
continue; continue;
} }
let hits = osnap_in( let Some((cands, prims)) = collect_in(d, &model, &model_ix, model_cursor, model_aperture, osmode, &view.viewport.frozen_layers) else {
d, continue;
&model, };
&model_ix, let clip = Some(view.model_clip);
model_cursor, // The rank was found in model units: paper units are model units times the scale.
model_aperture, let project = |(h, r): (SnapHit, Rank)| Some((view.hit(h)?, Rank { score: r.score * view.scale, ..r }));
osmode, let first = finish(cands.clone(), &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip);
model_base, // The model clip is the box round the viewport as the model sees it, larger than the
deferred, // viewport when it is twisted: a snap inside it can still fall off the viewport. Then the
&view.viewport.frozen_layers, // best of the others that is on it, as Tab ranks them.
Some(view.model_clip), let hit = first.and_then(|f| {
); project(f)
if let Some(hit) = hits.first().and_then(|h| view.hit(*h)) .or_else(|| finish_all(cands, &prims, model_cursor, model_aperture, osmode, model_base, deferred, clip).into_iter().find_map(project))
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture)) });
if let Some((hit, rank)) = hit
&& best.as_ref().is_none_or(|(_, b)| rank.beats(b))
{ {
pick = Some(hit); best = Some((hit, rank));
}
all.extend(hits.into_iter().filter_map(|h| view.hit(h)));
}
let mut out = ranked(all, cursor, aperture);
if let Some(pick) = pick {
out.retain(|h| !h.same(&pick));
out.insert(0, pick);
}
(out, near_prims)
}
/// `hits` best first ([`SnapHit::rank`]), without repeats.
fn ranked(mut hits: Vec<SnapHit>, cursor: Vec2, aperture: f64) -> Vec<SnapHit> {
hits.sort_by(|a, b| {
let (ca, sa) = a.rank(cursor, aperture);
let (cb, sb) = b.rank(cursor, aperture);
ca.cmp(&cb).then(sa.total_cmp(&sb))
});
let mut out: Vec<SnapHit> = Vec::with_capacity(hits.len());
for h in hits {
if !out.iter().any(|o| o.same(&h)) {
out.push(h);
} }
} }
out (best.map(|(h, _)| h), near_prims)
} }
#[allow(clippy::too_many_arguments)] /// How a hit ranks against the hits of another space (paper space, another viewport) and, for
fn osnap_in( /// Tab, against the other candidates: first the order [`finish`] tries them in (snap points, then
d: &Drawing, /// a perpendicular or tangent on the object under the cursor or a center found from its curve,
space: &Space, /// then deferred snaps, then Nearest), then its score within that tier, in the units of the cursor.
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>, #[derive(Clone, Copy, Debug)]
cursor: Vec2, struct Rank {
aperture: f64, tier: u8,
osmode: u32, score: f64,
base: Option<Vec2>, }
deferred: bool,
frozen: &[String], impl Rank {
clip: Option<Bounds2>, fn cmp(&self, other: &Rank) -> std::cmp::Ordering {
) -> Vec<SnapHit> { self.tier.cmp(&other.tier).then(self.score.total_cmp(&other.score))
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default() }
fn beats(&self, other: &Rank) -> bool {
self.cmp(other).is_lt()
}
} }
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn osnap_in_with_prims( fn osnap_in_with_prims(
d: &Drawing, d: &Drawing,
@@ -384,7 +354,92 @@ fn osnap_in_with_prims(
deferred: bool, deferred: bool,
frozen: &[String], frozen: &[String],
clip: Option<Bounds2>, clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> { ) -> 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>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?; let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions // Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects // meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -422,8 +477,7 @@ fn osnap_in_with_prims(
} }
} }
} }
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip); Some((cands, near_prims))
Some((hits, near_prims))
} }
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> { fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -465,19 +519,6 @@ pub(crate) fn extendable(p: &Prim) -> bool {
matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. }) matches!(p, Prim::Seg(_) | Prim::Circle(_) | Prim::Infinite { .. })
} }
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
/// when the drawing can't be searched.
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, &[], None)
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than /// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
/// `skip` (and on the objects inside block references), with the object's direction there (a unit /// `skip` (and on the objects inside block references), with the object's direction there (a unit
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic /// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
@@ -528,8 +569,10 @@ pub(crate) fn nearest_with_direction(
best.map(|(_, at, dir)| (at, dir)) best.map(|(_, at, dir)| (at, dir))
} }
/// The snap candidates of `osmode` and the primitives within `aperture` of `cursor`; `None`
/// when the drawing can't be searched.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn gather_in( pub(crate) fn gather_in(
d: &Drawing, d: &Drawing,
space: &Space, space: &Space,
ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>, ix: &Option<std::sync::Arc<crate::spatial::SpatialIndex>>,
@@ -603,8 +646,19 @@ fn gather_in(
Some((cands, near_prims)) Some((cands, near_prims))
} }
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent /// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps, with
/// snaps, the deferred snaps and Nearest. /// 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.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn finish( fn finish(
mut cands: Vec<(u32, Vec2)>, mut cands: Vec<(u32, Vec2)>,
@@ -615,71 +669,192 @@ fn finish(
base: Option<Vec2>, base: Option<Vec2>,
deferred: bool, deferred: bool,
clip: Option<Bounds2>, clip: Option<Bounds2>,
) -> Vec<SnapHit> { ) -> Option<(SnapHit, Rank)> {
// Perpendicular / tangent from the base point. let from_base = base_snaps(near_prims, osmode, base, cursor, deferred);
if let Some(bp) = base { cands.extend(from_base.iter().map(|f| (f.mode, f.point)));
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)); let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let mut hits: Vec<SnapHit> = // Prefer more specific modes when nearly equidistant.
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect(); let best = cands
if base.is_none() && deferred { .iter()
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip)); .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 }));
}
// 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 osmode & mode::NEA != 0 { if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order. // The closest point of all nearby objects, whatever their drawing order.
let mut nb: Option<(f64, Vec2)> = None; let nb = near_prims.iter().filter_map(|p| nearest_point(p, cursor, aperture, &visible)).min_by(|a, b| a.0.total_cmp(&b.0));
let mut consider = |c: Vec2| { if let Some((score, p)) = nb {
let dd = c.dist(cursor); return Some((SnapHit::plain(mode::NEA, p), Rank { tier: 3, score }));
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 {
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
} }
} }
ranked(hits, cursor, aperture) 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. /// Prefer more specific modes when nearly equidistant.
@@ -687,6 +862,61 @@ 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 } 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). /// Upper bound on the block-reference objects one snap query looks at (hostile files).
const MAX_BLOCK_LEAVES: usize = 20_000; const MAX_BLOCK_LEAVES: usize = 20_000;
@@ -1002,11 +1232,15 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
} }
} }
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and /// Every deferred tangent and perpendicular within `aperture` of `cursor`, for Tab: one per curve
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the /// and mode, in drawing order (the caller ranks them), so Tab can go from the tangent to the
/// perpendicular on the same circle. /// 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> { fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new(); let mut hits = Vec::new();
if osmode & (mode::TAN | mode::PER) == 0 {
return hits;
}
for p in prims { for p in prims {
let curve = match p { let curve = match p {
Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }, Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius },
@@ -1039,6 +1273,45 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
hits 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;
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,
};
let (m, name, at) = match curve {
SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => {
(mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => {
(mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor))
}
SnapCurve::Line { a, b } if osmode & mode::PER != 0 => {
// Pick on the drawn extent: a segment's own span, an xline/ray anywhere.
let l = cadcraft_geom::Line::new(a, b);
(mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) })
}
_ => continue,
};
let dd = at.dist(cursor);
if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) {
best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }));
}
}
best.map(|(_, h)| h)
}
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two /// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
/// endpoints (in the order given), or `None` when there is no such line (a point inside the /// endpoints (in the order given), or `None` when there is no such line (a point inside the
/// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to /// circle it should be tangent to, concentric circles, non-parallel lines both perpendicular to
@@ -1444,21 +1717,22 @@ mod tests {
assert_eq!(h.name, "Intersection"); assert_eq!(h.name, "Intersection");
} }
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection /// Tab cycling sees every snap within the aperture: snap points nearest first (Intersection
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap` /// favoured), then Nearest on each object, and no snap twice; the first is what `osnap` picks.
/// picks. /// On a circle with no base point, its quadrant, then the deferred tangent and the deferred
/// perpendicular at the same spot.
#[test] #[test]
fn osnap_all_ranks_every_candidate() { fn osnap_all_ranks_every_candidate() {
let d = drawing(); let d = drawing();
let modes = mode::END | mode::MID | mode::INT | mode::NEA; let (cursor, modes) = (Vec2::new(5.2, 0.2), mode::END | mode::MID | mode::INT | mode::NEA);
let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false); let all = osnap_all(&d, &Space::Model, cursor, 0.5, modes, None, false);
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}"); // Both lines' midpoints are the intersection point: one Midpoint. Each line has its Nearest.
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point); assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA, mode::NEA], "{all:?}");
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot. 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 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(); 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_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, modes, None, false).is_empty()); 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] #[test]
@@ -1477,6 +1751,70 @@ mod tests {
assert!(h.point.near(Vec2::new(3.0, 0.0), 1e-9)); 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] #[test]
fn ortho_and_polar() { fn ortho_and_polar() {
assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0)); assert_eq!(ortho(Vec2::ZERO, Vec2::new(5.0, 1.0)), Vec2::new(5.0, 0.0));
@@ -1519,9 +1857,14 @@ mod tests {
let df = h.deferred.unwrap(); let df = h.deferred.unwrap();
assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 }); assert_eq!(df.curve, SnapCurve::Circle { center: Vec2::new(20.0, 0.0), radius: 2.0 });
assert_eq!(h.input(), crate::Input::Deferred(df)); assert_eq!(h.input(), crate::Input::Deferred(df));
// With a base it is an ordinary tangent. // 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)), true).unwrap(); 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();
assert!(t.deferred.is_none() && t.name == "Tangent"); 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. // 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(); let q = osnap(&d, &Space::Model, at, 0.5, mode::TAN | mode::QUA, None, true).unwrap();
assert_eq!(q.mode, mode::QUA); assert_eq!(q.mode, mode::QUA);
+47 -8
View File
@@ -482,13 +482,38 @@ impl Tracker {
cfg: &TrackConfig, cfg: &TrackConfig,
base: Option<Vec2>, base: Option<Vec2>,
) -> Option<Track> { ) -> Option<Track> {
let t = self.find(d, space, cursor, aperture, tol, cfg, base); 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);
self.last = t.clone(); self.last = t.clone();
t t
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
fn find(&self, d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, tol: f64, cfg: &TrackConfig, base: Option<Vec2>) -> Option<Track> { fn find(
&self,
d: &Drawing,
space: &Space,
cursor: Vec2,
aperture: f64,
tol: f64,
cfg: &TrackConfig,
base: Option<Vec2>,
frozen: &[String],
) -> Option<Track> {
if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) { if !(cursor.is_finite() && aperture.is_finite() && tol.is_finite() && aperture > 0.0 && tol > 0.0) {
return None; return None;
} }
@@ -538,7 +563,7 @@ impl Tracker {
// 2. A path crossing an object. // 2. A path crossing an object.
if cfg.running(mode::INT | mode::APP) { if cfg.running(mode::INT | mode::APP) {
let ix = crate::spatial::index(d, space); let ix = crate::spatial::index(d, space);
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default(); let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p)| p).unwrap_or_default();
for prim in prims.iter().take(200) { for prim in prims.iter().take(200) {
let extend = cfg.running(mode::APP) && super::extendable(prim); let extend = cfg.running(mode::APP) && super::extendable(prim);
for seg in super::prim_segments(prim) { for seg in super::prim_segments(prim) {
@@ -588,12 +613,26 @@ pub fn candidate(
aperture: f64, aperture: f64,
cfg: &TrackConfig, cfg: &TrackConfig,
base: Option<Vec2>, 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> { ) -> Option<Acquired> {
if !can_acquire(cursor, aperture, cfg) { if !can_acquire(cursor, aperture, cfg) {
return None; return None;
} }
let ix = crate::spatial::index(d, space); let ix = crate::spatial::index(d, space);
let prims = super::gather(d, space, &ix, cursor, aperture, mode::NEA).map(|(_, p)| p).unwrap_or_default(); let prims = super::gather_in(d, space, &ix, cursor, aperture, mode::NEA, frozen, None).map(|(_, p)| p).unwrap_or_default();
candidate_from_prims(cursor, hit, aperture, cfg, base, &prims) candidate_from_prims(cursor, hit, aperture, cfg, base, &prims)
} }
@@ -789,7 +828,7 @@ impl crate::Session {
s.orthomode ^= q.shift; s.orthomode ^= q.shift;
let angbase = self.angle_settings().angbase; let angbase = self.angle_settings().angbase;
let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } }; let Ok(st) = self.state() else { return CursorSnap { point: raw, ..Default::default() } };
let (doc, space) = (st.doc.clone(), st.edit_space()); let (doc, space, frozen) = (st.doc.clone(), st.edit_space(), st.viewport_frozen().to_vec());
if !raw.is_finite() { if !raw.is_finite() {
return CursorSnap { point: raw, ..Default::default() }; return CursorSnap { point: raw, ..Default::default() };
} }
@@ -798,10 +837,10 @@ impl crate::Session {
let cfg = TrackConfig::relative_to(&s, angbase, last); let cfg = TrackConfig::relative_to(&s, angbase, last);
let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 }; let osmode = s.osmode | if s.osnaphatch { mode::HATCH } else { 0 };
let ix = crate::spatial::index(&doc, &space); 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); let (hit, near_prims) = super::osnap_with_neighborhood(&doc, &space, &ix, raw, q.aperture, osmode, q.base, q.deferred, &frozen);
let cand = match (osmode & mode::HATCH, near_prims.as_deref()) { 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), (0, Some(prims)) => candidate_with_prims(raw, hit.as_ref(), q.aperture, &cfg, q.base, prims),
_ => candidate(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base), _ => candidate_with_frozen(&doc, &space, raw, hit.as_ref(), q.aperture, &cfg, q.base, &frozen),
}; };
let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift); let wait = self.tracking.hover(cand, q.now, cfg.shift_acquire, q.shift);
if let Some(h) = hit { if let Some(h) = hit {
@@ -816,7 +855,7 @@ impl crate::Session {
let (origin, angle) = super::grid_frame_in(&doc, &space); let (origin, angle) = super::grid_frame_in(&doc, &space);
p = super::grid_snap(p, doc.header.snap_unit(), origin, angle); p = super::grid_snap(p, doc.header.snap_unit(), origin, angle);
} }
if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) { if let Some(mut t) = self.tracking.track_with_frozen(&doc, &space, p, q.aperture, q.tol, &cfg, q.base, &frozen) {
// PolarSnap (SNAPTYPE 1): steps of POLARDIST, or of the snap X spacing when it is 0. // 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 }; let step = if s.polardist > 0.0 { s.polardist } else { s.snapunit.x };
if s.snapmode if s.snapmode
+1 -74
View File
@@ -90,8 +90,6 @@ pub struct SpatialIndex {
blocks: BTreeMap<String, Arc<Block>>, blocks: BTreeMap<String, Arc<Block>>,
dim_styles: Vec<DimStyle>, dim_styles: Vec<DimStyle>,
dimscale: f64, dimscale: f64,
/// ATTMODE: a block reference takes room for the constant attribute values it shows.
attmode: i64,
/// Annotation scale factor and ANNOALLVISIBLE: annotative objects measure at that scale. /// Annotation scale factor and ANNOALLVISIBLE: annotative objects measure at that scale.
anno: (u64, bool), anno: (u64, bool),
/// Layers turned off or frozen: block contents on them take no room in their inserts. /// Layers turned off or frozen: block contents on them take no room in their inserts.
@@ -144,7 +142,7 @@ impl SpatialIndex {
} }
/// Build, reusing `prev` for chunks the two stores share (only when the bounds context — /// Build, reusing `prev` for chunks the two stores share (only when the bounds context —
/// blocks, dimension styles, DIMSCALE, ATTMODE, hidden layers — is the same). /// blocks, dimension styles, DIMSCALE, hidden layers — is the same).
fn build_from(d: &Drawing, store: &EntityStore, prev: Option<&SpatialIndex>) -> SpatialIndex { fn build_from(d: &Drawing, store: &EntityStore, prev: Option<&SpatialIndex>) -> SpatialIndex {
let prev = prev.filter(|p| p.same_context(d)); let prev = prev.filter(|p| p.same_context(d));
let old: std::collections::HashMap<usize, Arc<ChunkIx>> = let old: std::collections::HashMap<usize, Arc<ChunkIx>> =
@@ -182,7 +180,6 @@ impl SpatialIndex {
blocks: (*d.blocks).clone(), blocks: (*d.blocks).clone(),
dim_styles: d.dim_styles.to_vec(), dim_styles: d.dim_styles.to_vec(),
dimscale: d.header.f64("DIMSCALE", 1.0), dimscale: d.header.f64("DIMSCALE", 1.0),
attmode: d.header.i64("ATTMODE", 1),
anno: anno_key(d), anno: anno_key(d),
hidden_layers: hidden_layers(d).map(str::to_owned).collect(), hidden_layers: hidden_layers(d).map(str::to_owned).collect(),
chunks, chunks,
@@ -197,7 +194,6 @@ impl SpatialIndex {
self.blocks.len() == d.blocks.len() self.blocks.len() == d.blocks.len()
&& self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b)) && self.blocks.iter().zip(&d.blocks).all(|((ka, a), (kb, b))| ka == kb && Arc::ptr_eq(a, b))
&& self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits() && self.dimscale.to_bits() == d.header.f64("DIMSCALE", 1.0).to_bits()
&& self.attmode == d.header.i64("ATTMODE", 1)
&& self.dim_styles == *d.dim_styles && self.dim_styles == *d.dim_styles
&& self.anno == anno_key(d) && self.anno == anno_key(d)
&& self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d)) && self.hidden_layers.iter().map(String::as_str).eq(hidden_layers(d))
@@ -429,7 +425,6 @@ mod tests {
explodable: true, explodable: true,
units: 0, units: 0,
array: None, array: None,
xref_stamp: None,
}; };
blk.entities 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 }))); .push(Entity::new(cadcraft_doc::Handle(1_000_000), EntityKind::Circle(cadcraft_doc::Circle { center: v3(0.0, 0.0), radius: 1.0 })));
@@ -773,74 +768,6 @@ mod tests {
assert_eq!(select::select_window(&d, &Space::Model, small, false), vec![h]); assert_eq!(select::select_window(&d, &Space::Model, small, false), vec![h]);
} }
/// ATTMODE decides whether a reference shows its block's constant attribute values, and so
/// whether they take room in its bounds, without touching the space or the block table: the
/// index must not be reused across a change of it.
#[test]
fn index_follows_attmode_for_constant_attribute_values() {
let mut d = Drawing::new_imperial();
let mut blk = (**drawing(1, 0).blocks.get("B").unwrap()).clone();
let text = cadcraft_doc::Text {
insert: v3(0.0, 500.0),
align_pt: None,
height: 1.0,
value: "C4".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
};
let def = cadcraft_doc::Attrib {
tag: "C".into(),
text,
invisible: false,
constant: true,
prompt: String::new(),
props: Default::default(),
multiline: None,
modes: Default::default(),
};
blk.entities.push(Entity { handle: cadcraft_doc::Handle(2_000_000), common: Common::default(), kind: EntityKind::AttDef(def) });
d.blocks.insert("B".into(), Arc::new(blk));
for i in 0..MIN_INDEXED {
let x = 1000.0 + i as f64;
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: v3(x, 0.0), b: v3(x, 1.0) })).unwrap();
}
let insert = Insert {
block: "B".into(),
insert: v3(0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
d.header.set_i64("ATTMODE", 0);
let hidden = SpatialIndex::build(&d, &d.model);
d.header.set_i64("ATTMODE", 1);
assert!(!hidden.matches(&d, &d.model));
let reused = SpatialIndex::build_from(&d, &d.model, Some(&hidden));
let fresh = SpatialIndex::build(&d, &d.model);
let last = u32::try_from(MIN_INDEXED).unwrap();
assert_eq!(reused.bounds(last), fresh.bounds(last));
assert_ne!(fresh.bounds(last), hidden.bounds(last), "the value shown at ATTMODE 1 takes room");
// The top-down picker skips a chunk whose cached envelope misses the query: a box at the
// value, far above everything else, must reach the reference through the reused index.
let at_value = Bounds2::new(Vec2::new(-1.0, 499.0), Vec2::new(3.0, 502.0));
let top = |ix: &SpatialIndex| ix.top_down(&at_value, false, usize::MAX).unwrap().map(|(i, _, _)| i).collect::<Vec<u32>>();
assert_eq!(top(&reused), vec![last], "the reference is found at its value");
assert_eq!(top(&reused), top(&fresh));
assert_eq!(Some(top(&reused)), reused.query(&at_value, false), "as the tree finds it");
assert!(top(&hidden).is_empty(), "nothing is there while the value is hidden");
}
#[test] #[test]
fn small_spaces_are_scanned() { fn small_spaces_are_scanned() {
let d = drawing(1, MIN_INDEXED - 1); let d = drawing(1, MIN_INDEXED - 1);
-12
View File
@@ -3,7 +3,6 @@
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::{EngineError, Result, Session}; use crate::{EngineError, Result, Session};
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
mod table; mod table;
@@ -12,8 +11,6 @@ const SESSION_VARS: &[&str] = &[
"ATTREQ", "ATTREQ",
"OSMODE", "OSMODE",
"OSNAPHATCH", "OSNAPHATCH",
"HPSPACE",
"HPDOUBLE",
"ANNOAUTOSCALE", "ANNOAUTOSCALE",
"ORTHOMODE", "ORTHOMODE",
"POLARMODE", "POLARMODE",
@@ -88,8 +85,6 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
let v = match n.as_str() { let v = match n.as_str() {
"OSMODE" => json!(st.osmode), "OSMODE" => json!(st.osmode),
"OSNAPHATCH" => json!(i32::from(st.osnaphatch)), "OSNAPHATCH" => json!(i32::from(st.osnaphatch)),
"HPSPACE" => json!(s.last_used.hatch_spacing),
"HPDOUBLE" => json!(i32::from(s.last_used.hatch_double)),
// AutoCAD's values: positive on, negative off (4 = every annotative object). // AutoCAD's values: positive on, negative off (4 = every annotative object).
"ANNOAUTOSCALE" => json!(if st.annoautoscale { 4 } else { -4 }), "ANNOAUTOSCALE" => json!(if st.annoautoscale { 4 } else { -4 }),
// Paper units per drawing unit of the current annotation scale (1:50 → 0.02). // Paper units per drawing unit of the current annotation scale (1:50 → 0.02).
@@ -333,13 +328,6 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
// The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour. // The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour.
"CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?, "CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?,
"OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?, "OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?,
"HPSPACE" => {
s.last_used.hatch_spacing = as_f64(v).filter(|f| is_supported_hatch_pattern_scale(*f)).ok_or_else(|| EngineError::BadParams {
cmd: "setvar".into(),
msg: format!("HPSPACE must be greater than {MIN_HATCH_PATTERN_SCALE:e} drawing units"),
})?;
}
"HPDOUBLE" => s.last_used.hatch_double = table::int_value(v).filter(|i| (0..=1).contains(i)).ok_or_else(bad)? == 1,
"ANNOAUTOSCALE" => st.annoautoscale = as_i(v).filter(|i| (-4..=4).contains(i)).ok_or_else(bad)? > 0, "ANNOAUTOSCALE" => st.annoautoscale = as_i(v).filter(|i| (-4..=4).contains(i)).ok_or_else(bad)? > 0,
// A scale of the drawing's list; ANNOAUTOSCALE adds it to the annotative objects. // A scale of the drawing's list; ANNOAUTOSCALE adds it to the annotative objects.
"CANNOSCALE" => crate::cmd::annoscale::set_current(s, v.as_str().ok_or_else(bad)?)?, "CANNOSCALE" => crate::cmd::annoscale::set_current(s, v.as_str().ok_or_else(bad)?)?,
+1 -3
View File
@@ -85,8 +85,6 @@ const HEADER: &[(&str, Kind, Def)] = &[
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted. // XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)), ("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. /// The standard lineweights in hundredths of a millimetre.
@@ -144,7 +142,7 @@ pub(super) fn get(s: &Session, name: &str) -> Option<Value> {
}) })
} }
pub(super) fn int_value(v: &Value) -> Option<i64> { fn int_value(v: &Value) -> Option<i64> {
match v { match v {
Value::Number(n) => n.as_i64().or_else(|| n.as_f64().filter(|f| f.fract() == 0.0 && f.abs() < 1e15).map(|f| f as i64)), Value::Number(n) => n.as_i64().or_else(|| n.as_f64().filter(|f| f.fract() == 0.0 && f.abs() < 1e15).map(|f| f as i64)),
Value::Bool(b) => Some(i64::from(*b)), Value::Bool(b) => Some(i64::from(*b)),
+2 -169
View File
@@ -598,15 +598,6 @@ fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new(); let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap(); let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let h2 = s
.doc_mut()
.unwrap()
.add(
&cadcraft_doc::Space::Model,
cadcraft_doc::Common::default(),
EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(10.0, 0.0, 5.0), b: cadcraft_geom::Vec3::new(15.0, 0.0, 8.0) }),
)
.unwrap();
s.doc_mut() s.doc_mut()
.unwrap() .unwrap()
.modify_entity(h, |e| { .modify_entity(h, |e| {
@@ -616,7 +607,7 @@ fn hot_grip_scale_scales_heights_and_thickness() {
} }
}) })
.unwrap(); .unwrap();
s.set_selection(vec![h, h2]); s.set_selection(vec![h]);
s.start_grip_edit(&[(h, 0)]).unwrap(); s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE // STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 { for _ in 0..3 {
@@ -629,165 +620,7 @@ fn hot_grip_scale_scales_heights_and_thickness() {
assert_eq!(e.common.thickness, 6.0); assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") }; let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0); assert_eq!(t.height, 4.0);
// Selected grip is the SCALE base point and must remain stationary in all three coordinates. assert_eq!(t.insert.z, 10.0);
assert!((t.insert.x - 10.0).abs() < 1e-9);
assert!(t.insert.y.abs() < 1e-9);
assert!((t.insert.z - 5.0).abs() < 1e-9);
let EntityKind::Line(l) = &s.doc().unwrap().entity(h2).unwrap().kind else { panic!("expected line") };
assert!((l.a.x - 10.0).abs() < 1e-9 && l.a.y.abs() < 1e-9 && (l.a.z - 5.0).abs() < 1e-9);
assert!((l.b.x - 20.0).abs() < 1e-9 && l.b.y.abs() < 1e-9 && (l.b.z - 11.0).abs() < 1e-9);
// JSON `grip.scale` using `index` also keeps the selected grip stationary in 3D.
s.execute("grip.scale", &json!({"handles": [h.hex()], "index": 0, "factor": 0.5})).unwrap();
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 3.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 2.0);
assert!((t.insert.x - 10.0).abs() < 1e-9 && t.insert.y.abs() < 1e-9 && (t.insert.z - 5.0).abs() < 1e-9);
}
#[test]
fn scale_reference_preview_and_drag() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Plain SCALE preview and drag.
for t in ["scale", "all", "", "0,0"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.preview(Vec2::new(2.0, 0.0)).len(), 2);
let (d, extra) = s.drag(Vec2::new(2.0, 0.0)).unwrap();
assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(20.0, 0.0), 1e-9));
assert_eq!(extra.len(), 1);
// Enter accepts default reference length 1.0, then drag/preview at new length, then Points option.
for t in ["r", ""] {
s.cmdline(t).unwrap();
}
assert_eq!(s.current_prompt().unwrap().message, "Specify new length");
let (d, extra) = s.drag(Vec2::new(3.0, 0.0)).unwrap();
assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(30.0, 0.0), 1e-9));
assert!(matches!(&extra[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::ZERO, 1e-9) && l.b.xy().near(Vec2::new(3.0, 0.0), 1e-9)));
assert_eq!(s.preview(Vec2::new(3.0, 0.0)).len(), 2);
s.cmdline("p").unwrap();
assert!(s.drag(Vec2::new(5.0, 0.0)).is_none());
assert!(s.preview(Vec2::new(5.0, 0.0)).is_empty());
s.cmdline("5,5").unwrap();
let (d, extra) = s.drag(Vec2::new(5.0, 7.0)).unwrap();
assert!(d.matrix.apply(Vec2::new(10.0, 0.0)).near(Vec2::new(20.0, 0.0), 1e-9));
assert!(matches!(&extra[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::new(5.0, 5.0), 1e-9) && l.b.xy().near(Vec2::new(5.0, 7.0), 1e-9)));
assert_eq!(s.preview(Vec2::new(5.0, 7.0)).len(), 2);
s.cmdline("").unwrap();
assert!(s.running.is_none());
}
#[test]
fn select_then_reference_cancel_and_previews() {
fn line_end(s: &Session) -> Vec2 {
let e = s.doc().unwrap().model.iter().next().unwrap();
let EntityKind::Line(l) = &e.kind else { panic!("expected line") };
l.b.xy()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference before length is given: no drag/preview; after first point, only rubber-band preview; Enter cancels.
for t in ["scale", "all", "", "0,0", "r"] {
s.cmdline(t).unwrap();
}
assert!(s.drag(Vec2::new(5.0, 0.0)).is_none());
assert!(s.preview(Vec2::new(5.0, 0.0)).is_empty());
s.cmdline("0,0").unwrap();
let pv = s.preview(Vec2::new(5.0, 0.0));
assert_eq!(pv.len(), 1);
assert!(matches!(&pv[0].kind, EntityKind::Line(l) if l.a.xy().near(Vec2::ZERO, 1e-9) && l.b.xy().near(Vec2::new(5.0, 0.0), 1e-9)));
assert!(s.drag(Vec2::new(5.0, 0.0)).is_none());
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert!(line_end(&s).near(Vec2::new(10.0, 0.0), 1e-9));
// COPY and ROTATE previews also emit transformed geometry plus rubber-band.
for cmd in ["copy", "rotate"] {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
for t in [cmd, "all", "", "0,0"] {
s.cmdline(t).unwrap();
}
assert_eq!(s.preview(Vec2::new(4.0, 3.0)).len(), 2);
s.input(Input::Cancel).unwrap();
}
}
#[test]
fn hot_grip_scale_and_reference_point_picks() {
let mut s = Session::new();
let rl = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
let l = cadcraft_doc::Handle::parse_hex(rl["handles"][0].as_str().unwrap()).unwrap();
let rt = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let t = cadcraft_doc::Handle::parse_hex(rt["handle"].as_str().unwrap()).unwrap();
s.doc_mut().unwrap().modify_entity(t, |e| e.common.thickness = 3.0).unwrap();
// Hot-grip SCALE: coincident point is rejected; valid point scales line, text height, and thickness.
s.set_selection(vec![l, t]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
s.cmdline("0,0").unwrap();
assert!(s.running.is_some());
s.cmdline("2,0").unwrap();
assert!(s.running.is_none());
let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") };
assert!(ln.b.xy().near(Vec2::new(20.0, 0.0), 1e-9));
let te = s.doc().unwrap().entity(t).unwrap();
assert_eq!(te.common.thickness, 6.0);
let EntityKind::Text(tx) = &te.kind else { panic!("expected text") };
assert_eq!(tx.height, 4.0);
// Hot-grip SCALE Reference: zero new length point is rejected; valid point scales back by 0.5.
s.set_selection(vec![l, t]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
for cmd in ["r", "20", "0,0"] {
s.cmdline(cmd).unwrap();
}
assert!(s.running.is_some());
s.cmdline("10,0").unwrap();
assert!(s.running.is_none());
let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") };
assert!(ln.b.xy().near(Vec2::new(10.0, 0.0), 1e-9));
let te = s.doc().unwrap().entity(t).unwrap();
assert_eq!(te.common.thickness, 3.0);
let EntityKind::Text(tx) = &te.kind else { panic!("expected text") };
assert_eq!(tx.height, 2.0);
// Hot-grip ROTATE Reference with picked new-angle point.
s.set_selection(vec![l]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..2 {
s.input(Input::Enter).unwrap();
}
for cmd in ["r", "0", "0,10"] {
s.cmdline(cmd).unwrap();
}
assert!(s.running.is_none());
let EntityKind::Line(ln) = &s.doc().unwrap().entity(l).unwrap().kind else { panic!("expected line") };
assert!(ln.b.xy().near(Vec2::new(0.0, 10.0), 1e-9));
// Hot-grip MIRROR with coincident point is rejected; eXit ends cleanly.
s.set_selection(vec![l]);
s.start_grip_edit(&[(l, 0)]).unwrap();
for _ in 0..4 {
s.input(Input::Enter).unwrap();
}
s.cmdline("0,0").unwrap();
assert!(s.running.is_some());
s.cmdline("x").unwrap();
assert!(s.running.is_none());
} }
#[test] #[test]
+8 -146
View File
@@ -218,46 +218,18 @@ fn one_undo_restores_everything() {
} }
#[test] #[test]
fn a_short_piece_on_the_kept_side_stays_as_trim_leaves_it() { fn never_leaves_a_piece_of_no_length() {
// Landing review of #2808: only pieces of no length go; a short one that has length stays.
let mut s = Session::new(); let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]); let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
// Starts a hair below the edge: trimming above leaves that hair. // Starts a hair below the edge: trimming above would leave a sliver.
line(&mut s, [5.0, -1e-8], [5.0, 5.0]); line(&mut s, [5.0, -1e-8], [5.0, 5.0]);
let v = extrim(&mut s, &edge, [5.0, 3.0]); extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["trimmed"], 1, "{v}");
let d = s.doc().unwrap(); let d = s.doc().unwrap();
let hairs: Vec<f64> = d for e in d.model.iter() {
.model if let EntityKind::Line(l) = &e.kind {
.iter() assert!(l.a.xy().dist(l.b.xy()) > 1e-6, "sliver left: {l:?}");
.filter_map(|e| match &e.kind { }
EntityKind::Line(l) if (l.a.x - 5.0).abs() < 1e-9 => Some(l.a.xy().dist(l.b.xy())), }
_ => None,
})
.collect();
assert_eq!(hairs.len(), 1, "{hairs:?}");
assert!((hairs[0] - 1e-8).abs() < 1e-12, "{hairs:?}");
}
#[test]
fn a_stretch_shorter_than_trims_on_cut_tolerance_is_left_and_reported() {
// Landing review of #2808: TRIM passes over a cut within 5e-7 of the pick and runs on to the
// next one, so it would take more than the planned stretch. Such a stretch is left instead.
let mut s = Session::new();
// A short edge, so the trace runs closer to it than that.
let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]);
// A polyline that pokes 4e-7 above the edge, comes back down and then rises well above it.
let verts = json!([[0.003, -5.0], [0.003, 4e-7], [0.0031, -5.0], [0.0031, 5.0]]);
s.execute("pline", &json!({ "vertices": verts })).unwrap();
line(&mut s, [0.007, -5.0], [0.007, 5.0]);
let v = extrim(&mut s, &edge, [0.005, 3.0]);
assert_eq!(v["trimmed"], 1, "the line: {v}");
assert_eq!(v["skipped"]["uncut"], 1, "the polyline: {v}");
assert_eq!(v["skipped"]["partly"], 1, "its tall stretch is still cut: {v}");
// The polyline's start is still there: the poke's trim didn't run on to the rise.
let start = Vec2::new(0.003, -5.0);
assert!(points_but(&s, &edge).iter().any(|p| p.near(start, 1e-9)), "the start below the edge was taken");
assert!(top_but(&s, &edge) < 1e-6, "{}", top_but(&s, &edge));
} }
#[test] #[test]
@@ -548,113 +520,3 @@ fn large_radius_arcs_weaving_through_a_short_edge_lose_every_stretch_on_the_side
.fold(f64::NEG_INFINITY, f64::max); .fold(f64::NEG_INFINITY, f64::max);
assert!(above <= 1e-6, "a stretch above the edge was left: {above:e}"); assert!(above <= 1e-6, "a stretch above the edge was left: {above:e}");
} }
#[test]
fn the_preview_cap_counts_drawn_parts_not_objects() {
// One zigzag polyline with `k` teeth above the edge loses `k` stretches: one object, `k` parts
// to draw. The preview draws up to 2000 parts (landing review of #2808).
for (k, previewed) in [(1999usize, true), (2001, false)] {
let mut s = Session::new();
let edge = line(&mut s, [-1.0, 0.0], [2.0 * k as f64 + 1.0, 0.0]);
let verts: Vec<[f64; 2]> = (0..=2 * k).map(|i| [i as f64, if i % 2 == 0 { -1.0 } else { 1.0 }]).collect();
s.execute("pline", &json!({ "vertices": verts })).unwrap();
s.set_selection(Vec::new());
s.start("extrim").unwrap();
s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap();
let shown = s.preview(Vec2::new(5.0, 3.0));
assert_eq!(!shown.is_empty(), previewed, "{k} teeth: {} shown", shown.len());
// Past the cap the trim itself still takes every tooth.
s.input(Input::Point(Vec2::new(5.0, 3.0))).unwrap();
assert!(top_but(&s, &edge) <= 1e-6, "{k} teeth: {}", top_but(&s, &edge));
}
}
#[test]
fn a_short_piece_far_from_the_origin_stays_too() {
// #3526 review: the deletion test is no tolerance that grows with the distance from the
// origin. Near x = 1e9 a 1e-5 piece is a real piece.
let mut s = Session::new();
let edge = line(&mut s, [1e9, 0.0], [1e9 + 10.0, 0.0]);
line(&mut s, [1e9 + 5.0, -1e-5], [1e9 + 5.0, 5.0]);
let v = extrim(&mut s, &edge, [1e9 + 5.0, 3.0]);
assert_eq!(v["trimmed"], 1, "{v}");
let d = s.doc().unwrap();
let kept: Vec<f64> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) if (l.a.x - (1e9 + 5.0)).abs() < 1e-6 => Some(l.a.xy().dist(l.b.xy())),
_ => None,
})
.collect();
assert_eq!(kept.len(), 1, "{kept:?}");
assert!((kept[0] - 1e-5).abs() < 1e-9, "{kept:?}");
}
#[test]
fn the_preview_leaves_out_a_stretch_the_trim_leaves() {
// #3526 review: the poke too short for TRIM to cut alone is not previewed as going.
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]);
let verts = json!([[0.003, -5.0], [0.003, 4e-7], [0.0031, -5.0], [0.0031, 5.0]]);
s.execute("pline", &json!({ "vertices": verts })).unwrap();
s.set_selection(Vec::new());
s.start("extrim").unwrap();
s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap();
let shown = s.preview(Vec2::new(0.005, 3.0));
let xs: Vec<f64> = shown
.iter()
.flat_map(|e| match &e.kind {
EntityKind::LwPolyline(p) => p.vertices.iter().map(|v| v.p.x).collect(),
_ => Vec::new(),
})
.collect();
assert!(!xs.is_empty(), "the rise is previewed");
assert!(xs.iter().all(|x| *x > 0.00305), "the poke is not: {xs:?}");
}
#[test]
fn the_preview_cap_counts_only_parts_it_draws() {
// #3526 review: stretches too short to trim are not drawn, so they don't count toward the cap.
// 2001 pokes 4e-7 above a short edge, and one line rising well above it.
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]);
for i in 0..2001 {
let x = 0.0005 + i as f64 * 4e-6;
line(&mut s, [x, -5.0], [x, 4e-7]);
}
line(&mut s, [0.009, -5.0], [0.009, 5.0]);
s.set_selection(Vec::new());
s.start("extrim").unwrap();
s.input(Input::Pick(vec![Handle::parse_hex(&edge).unwrap()])).unwrap();
let shown = s.preview(Vec2::new(0.005, 3.0));
assert_eq!(shown.len(), 1, "only the rise is drawn, under the cap");
}
#[test]
fn a_stretch_trim_can_cut_alone_is_cut_however_short() {
// #3526 review: a stretch is left only where TRIM would pass over its cut (within 5e-7 of the
// pick, plus the tracing's margin), not twice that. This one is 1.5e-6 long: the pick is
// 7.5e-7 from the cut, and TRIM cuts it.
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [0.01, 0.0]);
line(&mut s, [0.005, -0.005], [0.005, 1.5e-6]);
let v = extrim(&mut s, &edge, [0.005, 3.0]);
assert_eq!(v["trimmed"], 1, "{v}");
assert_eq!(v["skipped"]["uncut"], 0, "{v}");
assert!(top_but(&s, &edge) <= 1e-12, "{}", top_but(&s, &edge));
}
#[test]
fn a_folded_stretch_is_measured_along_itself() {
// #3526 review: the pick of this stretch is 1.5e-6 from its end straight across, where the
// polyline folds back, but two units from the cut along it: TRIM cuts it, and so does EXTRIM.
let mut s = Session::new();
let edge = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
let verts = json!([[1.0, -1.0], [1.0, 2.0], [1.5, 2.0], [1.5, 2.5], [1.0, 2.5], [1.0, 2.000001]]);
s.execute("pline", &json!({ "vertices": verts })).unwrap();
let v = extrim(&mut s, &edge, [5.0, 3.0]);
assert_eq!(v["trimmed"], 1, "{v}");
assert_eq!(v["skipped"]["uncut"], 0, "{v}");
assert!(top_but(&s, &edge) <= 1e-9, "the stretch above the edge is gone: {}", top_but(&s, &edge));
}
+3 -2
View File
@@ -126,6 +126,7 @@ mod offset_ellipse_side;
mod offset_move; mod offset_move;
mod oops_command; mod oops_command;
mod options_profile; mod options_profile;
mod osnap_opened_drawings;
mod overkill; mod overkill;
mod parallel_display_list; mod parallel_display_list;
mod pedit_heights; mod pedit_heights;
@@ -157,7 +158,6 @@ mod recent_commands;
mod rectang_ortho; mod rectang_ortho;
mod rectang_polygon_order; mod rectang_polygon_order;
mod refedit; mod refedit;
mod refedit_xref;
mod region; mod region;
mod rename_cmdline; mod rename_cmdline;
mod revcloud_recognised; mod revcloud_recognised;
@@ -174,10 +174,12 @@ mod setvar_coverage;
mod shapes; mod shapes;
mod snap_annotations; mod snap_annotations;
mod snap_blocks; mod snap_blocks;
mod snap_center_on_curve;
mod snap_curves; mod snap_curves;
mod snap_intersections_aperture; mod snap_intersections_aperture;
mod snap_nearest; mod snap_nearest;
mod snap_overrides; mod snap_overrides;
mod snap_tab_cycling;
mod snap_tracking; mod snap_tracking;
mod snaps_more; mod snaps_more;
mod solid_command; mod solid_command;
@@ -203,7 +205,6 @@ mod trim_keeps_z_and_width;
mod undo_count; mod undo_count;
mod undo_layout_tab; mod undo_layout_tab;
mod viewport_clip; mod viewport_clip;
mod viewport_frozen_block_parts;
mod viewport_frozen_selection; mod viewport_frozen_selection;
mod vplayer_prompts; mod vplayer_prompts;
mod vports; mod vports;
@@ -1,7 +1,8 @@
//! DIST snaps to the model geometry displayed in paper-space viewports (#516). //! DIST snaps to the model geometry displayed in paper-space viewports (#516).
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport}; use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Ellipse, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3}; 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, osnap_all};
use cadcraft_engine::{Input, Session}; use cadcraft_engine::{Input, Session};
use serde_json::json; use serde_json::json;
@@ -278,22 +279,22 @@ 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()); assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
} }
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap /// Across spaces a click takes the viewport's Endpoint over a paper-space Nearest that scores
/// replaces paper space's only when it scores closer. Tab still reaches the other one. /// 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] #[test]
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() { fn a_viewport_endpoint_beats_a_closer_paper_space_nearest() {
let (mut d, paper) = drawing(); 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). // 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(); 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 (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap(); let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}"); assert!(hit.mode == mode::END && hit.viewport.is_some() && hit.point.near(Vec2::new(95.0, 50.0), 1e-9), "{hit:?}");
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}"); let all = snap_candidates(&d, &paper, cursor, 0.5, modes, None, false);
let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false);
assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap"); assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap");
assert!( assert!(
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)), 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 viewport's endpoint: {all:?}" "Tab reaches the paper-space Nearest: {all:?}"
); );
} }
@@ -429,3 +430,50 @@ 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()); 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:?}");
}
@@ -0,0 +1,116 @@
//! 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,7 +104,6 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() {
explodable: true, explodable: true,
units: 0, units: 0,
array: None, array: None,
xref_stamp: None,
}; };
d.blocks.insert("*D1".into(), std::sync::Arc::new(block)); d.blocks.insert("*D1".into(), std::sync::Arc::new(block));
d.model.modify(dim, |e| { d.model.modify(dim, |e| {
+2 -3
View File
@@ -279,7 +279,7 @@ fn interactive_refedit_refset_and_refclose() {
} }
#[test] #[test]
fn an_xref_that_is_not_loaded_is_refused_with_a_message() { fn xrefs_are_refused_with_a_message() {
let mut s = Session::new(); let mut s = Session::new();
s.doc_mut().unwrap().blocks.insert( s.doc_mut().unwrap().blocks.insert(
"X".into(), "X".into(),
@@ -291,6 +291,5 @@ fn an_xref_that_is_not_loaded_is_refused_with_a_message() {
); );
let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0); let x = insert(&mut s, "X", (0.0, 0.0), 1.0, 0.0);
let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err(); let e = s.execute("refedit", &json!({ "handle": x })).unwrap_err();
// Xrefs are edited in place and written back (refedit_xref.rs); one not loaded can't be. assert!(e.to_string().contains("external reference"), "{e}");
assert!(e.to_string().contains("not loaded"), "{e}");
} }
File diff suppressed because it is too large Load Diff
+1 -6
View File
@@ -23,10 +23,8 @@ fn defaults_are_the_ones_the_commands_use() {
("TRIMMODE", json!(1)), ("TRIMMODE", json!(1)),
("PROJMODE", json!(1)), ("PROJMODE", json!(1)),
("EDGEMODE", json!(0)), ("EDGEMODE", json!(0)),
("HPDOUBLE", json!(0)),
("HPNAME", json!("ANSI31")), ("HPNAME", json!("ANSI31")),
("HPSCALE", json!(1.0)), ("HPSCALE", json!(1.0)),
("HPSPACE", json!(1.0)),
("HPANG", json!(0.0)), ("HPANG", json!(0.0)),
("DONUTID", json!(0.5)), ("DONUTID", json!(0.5)),
("DONUTOD", json!(1.0)), ("DONUTOD", json!(1.0)),
@@ -43,7 +41,7 @@ fn defaults_are_the_ones_the_commands_use() {
// Lowercase names work; the list shows the new variables and the dimension variables. // Lowercase names work; the list shows the new variables and the dimension variables.
assert_eq!(getvar(&mut s, "circlerad"), json!(0.0)); assert_eq!(getvar(&mut s, "circlerad"), json!(0.0));
let all = cadcraft_engine::sysvars::list(&s); let all = cadcraft_engine::sysvars::list(&s);
for n in ["POLYSIDES", "SPLINESEGS", "CHAMFERD", "TRANSPARENCYDISPLAY", "DIMASZ", "OSMODE", "CLAYER", "HPSPACE", "HPDOUBLE"] { for n in ["POLYSIDES", "SPLINESEGS", "CHAMFERD", "TRANSPARENCYDISPLAY", "DIMASZ", "OSMODE", "CLAYER"] {
assert!(all.get(n).is_some(), "{n} listed"); assert!(all.get(n).is_some(), "{n} listed");
} }
} }
@@ -85,9 +83,6 @@ fn bad_values_and_unknown_names_are_refused() {
("LAYLOCKFADECTL", json!(91)), ("LAYLOCKFADECTL", json!(91)),
("LAYLOCKFADECTL", json!(-91)), ("LAYLOCKFADECTL", json!(-91)),
("HPSCALE", json!(0)), ("HPSCALE", json!(0)),
("HPSPACE", json!(0)),
("HPDOUBLE", json!(2)),
("HPDOUBLE", json!(0.5)),
("HPNAME", json!("NO-SUCH-PATTERN")), ("HPNAME", json!("NO-SUCH-PATTERN")),
("DONUTOD", json!(0)), ("DONUTOD", json!(0)),
("CIRCLERAD", json!(-1)), ("CIRCLERAD", json!(-1)),
@@ -0,0 +1,202 @@
//! 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,6 +70,9 @@ 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"); let (q, m) = along_quarter(&s, mode::TAN, Some(base)).expect("a tangent point on the arc");
assert_eq!(m, mode::TAN); 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:?}"); 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. // Perpendicular from (10,10): the line from the base runs along the normal.
let base = Vec2::new(10.0, 10.0); 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"); let (q, m) = along_quarter(&s, mode::PER, Some(base)).expect("a perpendicular foot on the arc");
@@ -119,3 +122,28 @@ fn spline_midpoint_perpendicular_and_tangent() {
let d = (sp.eval(i + 1e-6) - sp.eval(i - 1e-6)).normalized(); 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:?}"); 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,6 +21,17 @@ 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() 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 { fn near(p: Vec2, x: f64, y: f64) -> bool {
p.near(Vec2::new(x, y), 1e-9) p.near(Vec2::new(x, y), 1e-9)
} }
@@ -80,6 +91,23 @@ fn nothing_to_snap_to_rejects_the_point() {
assert!(near(s.last_point, 10.0, 10.0)); 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] #[test]
fn from_nests_with_a_snap_override() { fn from_nests_with_a_snap_override() {
let mut s = drawing(); let mut s = drawing();
@@ -116,3 +144,97 @@ fn a_command_keyword_wins_over_a_snap_word() {
s.cmdline("arc _cen").unwrap(); s.cmdline("arc _cen").unwrap();
assert!(s.prompt_text().ends_with("Center of:"), "{}", s.prompt_text()); 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
@@ -0,0 +1,102 @@
//! 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:?}");
}
-19
View File
@@ -310,22 +310,3 @@ fn a_fence_across_more_objects_than_the_preview_cap_shows_no_part() {
s.input(Input::Enter).unwrap(); s.input(Input::Enter).unwrap();
assert!((before - drawn(&s) - (CAP + 1) as f64 * 10.0).abs() < 1e-6, "every rung lost its middle"); assert!((before - drawn(&s) - (CAP + 1) as f64 * 10.0).abs() < 1e-6, "every rung lost its middle");
} }
#[test]
fn a_short_piece_far_from_the_origin_is_highlighted_and_removed_as_near_it() {
// #3382 landing review: the tolerance that merges nearby cuts must not grow with the distance
// from the origin, or a visible 0.5-unit piece near x = 1e9 is merged away.
for x0 in [0.0, 1e9] {
let mut s = Session::new();
line(&mut s, [x0 + 5.0, -5.0], [x0 + 5.0, 5.0]);
line(&mut s, [x0 + 5.5, -5.0], [x0 + 5.5, 5.0]);
let l = line(&mut s, [x0, 0.0], [x0 + 10.0, 0.0]);
s.zoom_extents().unwrap();
s.start("trim").unwrap();
let shown = highlight(&s, l, [x0 + 5.25, 0.0]).unwrap_or_else(|| panic!("at {x0}: the whole line is highlighted"));
assert!((length(&shown) - 0.5).abs() < 1e-3, "at {x0}: {}", length(&shown));
let before = drawn(&s);
s.input(Input::Point(Vec2::new(x0 + 5.25, 0.0))).unwrap();
assert!((before - drawn(&s) - 0.5).abs() < 1e-3, "at {x0}: the click removes the same 0.5");
}
}
File diff suppressed because it is too large Load Diff
@@ -781,55 +781,3 @@ fn a_small_and_a_large_selection_leave_out_the_same_objects() {
s.set_selection(all.clone()); s.set_selection(all.clone());
assert_eq!(s.selection(), all); assert_eq!(s.selection(), all);
} }
/// EXTRIM through a viewport leaves the objects on layers frozen there, as a fence through it
/// selects only what it draws (landing review of #2808).
#[test]
fn extrim_through_a_viewport_leaves_layers_frozen_there() {
for (frozen_here, hidden_trimmed) in [(true, false), (false, true)] {
let Sheet { mut s, shown, hidden, a, b } = sheet();
enter(&mut s, if frozen_here { &a } else { &b });
let edge = line(&mut s, [5.0, -5.0], [5.0, 5.0]);
s.execute("extrim", &json!({ "edge": edge.hex(), "side": [8.0, 1.0] })).unwrap();
assert!(edited(&s, shown), "the drawn line is trimmed");
assert_eq!(edited(&s, hidden), hidden_trimmed, "frozen in this viewport: {frozen_here}");
}
}
/// #3526 review: EXTRIM's preview follows a change of the frozen layers while it runs.
#[test]
fn extrims_preview_follows_the_frozen_layers_while_it_runs() {
let Sheet { mut s, b, .. } = sheet();
enter(&mut s, &b);
let edge = line(&mut s, [5.0, -5.0], [5.0, 5.0]);
s.set_selection(Vec::new());
s.start("extrim").unwrap();
s.input(cadcraft_engine::Input::Pick(vec![edge])).unwrap();
let side = Vec2::new(8.0, 1.0);
assert_eq!(s.preview(side).len(), 2, "both lines lose their right half");
s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap();
assert!(s.running.is_some(), "EXTRIM is still running");
assert_eq!(s.preview(side).len(), 1, "the line now frozen here is left, and not previewed");
}
/// #3526 review: a cutting edge picked in paper space cuts nothing once MSPACE moves into a
/// viewport, so EXTRIM previews nothing there and the trim is refused with the drawing unchanged.
#[test]
fn an_extrim_edge_left_in_paper_space_previews_and_cuts_nothing_in_a_viewport() {
let Sheet { mut s, shown, hidden, b, .. } = sheet();
// In paper space: an edge and one line crossing it, where model space has two.
let edge = line(&mut s, [5.0, -5.0], [5.0, 5.0]);
let paper = line(&mut s, [0.0, 0.0], [10.0, 0.0]);
s.set_selection(Vec::new());
s.start("extrim").unwrap();
s.input(cadcraft_engine::Input::Pick(vec![edge])).unwrap();
let side = Vec2::new(8.0, 1.0);
assert_eq!(s.preview(side).len(), 1, "paper space: its one line");
s.execute("mspace", &json!({ "handle": b })).unwrap();
assert_eq!(s.space(), Space::Model);
assert!(s.viewport_frozen().is_empty(), "the viewport freezes nothing");
assert!(s.running.is_some(), "EXTRIM is still running");
assert!(s.preview(side).is_empty(), "the edge is not in model space: nothing previewed");
let _ = s.input(cadcraft_engine::Input::Point(side));
assert!(untouched(&s, shown) && untouched(&s, hidden) && untouched(&s, paper), "nothing was trimmed");
}
-33
View File
@@ -305,36 +305,3 @@ fn drawings_sharing_a_name_keep_their_own_backups() {
assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak"); assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak");
assert_eq!(name("x/plan.dwt"), "x/plan.dwt.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);
}
+1 -1
View File
@@ -27,7 +27,7 @@ pub mod windows;
use cadcraft_geom::{Bounds2, Vec2}; use cadcraft_geom::{Bounds2, Vec2};
pub use mtext::para::{DEFAULT_TAB, ListStyle, MTextColumnSpec, ParaAlign, ParaLineSpacing, ParaProps, Paragraphs, TabKind, list_contents}; pub use mtext::para::{DEFAULT_TAB, ListStyle, MTextColumnSpec, ParaAlign, ParaProps, Paragraphs, TabKind, list_contents};
pub use mtext::{MTextColor, MTextLayout, MTextParams, MTextPiece, layout_mtext, layout_mtext_with, plain_mtext}; pub use mtext::{MTextColor, MTextLayout, MTextParams, MTextPiece, layout_mtext, layout_mtext_with, plain_mtext};
mod craft_fonts; mod craft_fonts;
+10 -131
View File
@@ -1,7 +1,7 @@
//! MTEXT paragraph formatting and columns: the `\p…;` paragraph codes (first-line, left and //! MTEXT paragraph formatting and columns: the `\p…;` paragraph codes (first-line, left and
//! right indents, tab stops, alignment, line spacing, space before and after), tab characters //! right indents, tab stops, alignment, space before and after), tab characters (bulleted and
//! (bulleted and numbered lists are a label, a tab and a hanging indent), column breaks (`\N`) //! numbered lists are a label, a tab and a hanging indent), column breaks (`\N`) and text
//! and text flowing through static or dynamic columns. //! flowing through static or dynamic columns.
//! //!
//! Contents without any of these lay out exactly as in [`super::layout_mtext_with`]'s plain path. //! Contents without any of these lay out exactly as in [`super::layout_mtext_with`]'s plain path.
@@ -56,17 +56,6 @@ pub enum ParaAlign {
Distributed, Distributed,
} }
/// A paragraph's line spacing override (`\pxs…;`), overriding the entity's line spacing.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ParaLineSpacing {
/// `sm`: multiple spacing (grows for taller inline characters).
Multiple(f64),
/// `se`: exact spacing (uses the entity text height regardless of inline height changes).
Exact(f64),
/// `sd`: at-least spacing (grows for taller inline characters).
AtLeast(f64),
}
/// Paragraph properties set by `\p…;`. Indents and tab stops are in drawing units (as in /// Paragraph properties set by `\p…;`. Indents and tab stops are in drawing units (as in
/// `AutoCAD` files: `\pi4.86;` indents the first line by 4.86 units), space before and after in /// `AutoCAD` files: `\pi4.86;` indents the first line by 4.86 units), space before and after in
/// text heights. They stay in effect for the following paragraphs until another `\p` changes them. /// text heights. They stay in effect for the following paragraphs until another `\p` changes them.
@@ -80,8 +69,6 @@ pub struct ParaProps {
pub right: f64, pub right: f64,
/// `q`: alignment. /// `q`: alignment.
pub align: ParaAlign, pub align: ParaAlign,
/// `s`: paragraph line spacing (`None` uses the entity's line spacing).
pub line_spacing: Option<ParaLineSpacing>,
/// `t`: tab stops from the left edge, ascending. /// `t`: tab stops from the left edge, ascending.
pub tabs: Vec<(f64, TabKind)>, pub tabs: Vec<(f64, TabKind)>,
/// `b`: space before the paragraph. /// `b`: space before the paragraph.
@@ -153,25 +140,6 @@ impl ParaProps {
Some(_) => self.align, Some(_) => self.align,
} }
} }
's' => {
let rest = rest.trim();
if rest.is_empty() || rest == "*" {
self.line_spacing = None;
} else if let Some((mode, val)) = rest.split_at_checked(1) {
let val = val.trim();
let val = val.strip_suffix(['x', 'X']).unwrap_or(val).trim();
let factor = || num(val).filter(|v| *v > 0.0 && *v <= MAX_UNITS).map(super::sane_line_spacing);
match mode {
"m" | "e" | "d" if val == "*" => self.line_spacing = None,
"m" => self.line_spacing = factor().map(ParaLineSpacing::Multiple).or(self.line_spacing),
"e" => self.line_spacing = factor().map(ParaLineSpacing::Exact).or(self.line_spacing),
"d" => self.line_spacing = factor().map(ParaLineSpacing::AtLeast).or(self.line_spacing),
"b" => self.before = units(val).unwrap_or(self.before).max(0.0),
"a" => self.after = units(val).unwrap_or(self.after).max(0.0),
_ => {}
}
}
}
't' => { 't' => {
self.tabs.clear(); self.tabs.clear();
in_tabs = true; in_tabs = true;
@@ -203,24 +171,15 @@ impl ParaProps {
/// The `\p…;` code for these properties: the indents, then the right indent, spacing and /// The `\p…;` code for these properties: the indents, then the right indent, spacing and
/// alignment where they aren't the default, then the tab stops. /// alignment where they aren't the default, then the tab stops.
pub fn code(&self) -> String { pub fn code(&self) -> String {
self.code_after(&Self::default())
}
/// The `\p…;` code for these properties following `prev`: emits explicit resets (`s*`, `b0`,
/// `a0`) when a paragraph drops an earlier override back to the default.
pub fn code_after(&self, prev: &Self) -> String {
let n = |v: f64| { let n = |v: f64| {
let s = format!("{v:.4}"); let s = format!("{v:.4}");
let s = s.trim_end_matches('0').trim_end_matches('.'); let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".to_string() } else { s.to_string() } if s == "-0" { "0".to_string() } else { s.to_string() }
}; };
let mut items = vec![format!("i{}", n(self.first)), format!("l{}", n(self.left))]; let mut items = vec![format!("i{}", n(self.first)), format!("l{}", n(self.left))];
if self.right > 0.0 { for (key, v) in [('r', self.right), ('b', self.before), ('a', self.after)] {
items.push(format!("r{}", n(self.right))); if v > 0.0 {
} items.push(format!("{key}{}", n(v)));
for (key, v, prev_v) in [('b', self.before, prev.before), ('a', self.after, prev.after)] {
if v > 0.0 || prev_v > 0.0 {
items.push(format!("{key}{}", n(v.max(0.0))));
} }
} }
let q = match self.align { let q = match self.align {
@@ -232,14 +191,6 @@ impl ParaProps {
ParaAlign::Distributed => Some("qd"), ParaAlign::Distributed => Some("qd"),
}; };
items.extend(q.map(String::from)); items.extend(q.map(String::from));
let s = match self.line_spacing {
Some(ParaLineSpacing::Multiple(v)) => Some(format!("sm{}", n(v))),
Some(ParaLineSpacing::Exact(v)) => Some(format!("se{}", n(v))),
Some(ParaLineSpacing::AtLeast(v)) => Some(format!("sd{}", n(v))),
None if prev.line_spacing.is_some() => Some("s*".to_string()),
None => None,
};
items.extend(s);
for (i, (p, k)) in self.tabs.iter().enumerate() { for (i, (p, k)) in self.tabs.iter().enumerate() {
let kind = match k { let kind = match k {
TabKind::Left => "", TabKind::Left => "",
@@ -364,7 +315,7 @@ impl Paragraphs {
} }
static DEFAULT_PROPS: ParaProps = static DEFAULT_PROPS: ParaProps =
ParaProps { first: 0.0, left: 0.0, right: 0.0, align: ParaAlign::Default, line_spacing: None, tabs: Vec::new(), before: 0.0, after: 0.0 }; ParaProps { first: 0.0, left: 0.0, right: 0.0, align: ParaAlign::Default, tabs: Vec::new(), before: 0.0, after: 0.0 };
/// Contents or columns that need the paragraph layout. /// Contents or columns that need the paragraph layout.
pub(super) fn needed(contents: &str, p: &MTextParams) -> bool { pub(super) fn needed(contents: &str, p: &MTextParams) -> bool {
@@ -651,18 +602,11 @@ pub(super) fn layout(contents: &str, params: &MTextParams, base: &Fmt) -> MTextL
let mut col_bottom = vec![0.0f64]; let mut col_bottom = vec![0.0f64];
let mut prev_para: Option<usize> = None; let mut prev_para: Option<usize> = None;
for line in &lines { for line in &lines {
let pp = paragraphs.props(line.para);
let line_height = if line.max_h > 0.0 { line.max_h } else { height }; let line_height = if line.max_h > 0.0 { line.max_h } else { height };
let new_para = prev_para != Some(line.para); let new_para = prev_para != Some(line.para);
let before = if new_para && prev_para.is_some() { pp.before * height } else { 0.0 }; let before = if new_para && prev_para.is_some() { paragraphs.props(line.para).before * height } else { 0.0 };
let (exact, factor, floor) = match pp.line_spacing { let step_h = if params.line_spacing_exact { height } else { line_height };
Some(ParaLineSpacing::Multiple(v)) => (false, super::sane_line_spacing(v), 0.0), let pitch = |first: bool| if first { line_height } else { step_h * 5.0 / 3.0 * line_spacing + before };
Some(ParaLineSpacing::AtLeast(v)) => (false, super::sane_line_spacing(v), height),
Some(ParaLineSpacing::Exact(v)) => (true, super::sane_line_spacing(v), 0.0),
None => (params.line_spacing_exact, line_spacing, 0.0),
};
let step_h = if exact { height } else { line_height.max(floor) };
let pitch = |first: bool| if first { line_height } else { step_h * 5.0 / 3.0 * factor + before };
let column_height = col_height(column); let column_height = col_height(column);
if !first_in_col && column + 1 < max_cols && (force || (column_height > 0.0 && current_y + pitch(false) > column_height + 1e-9)) { if !first_in_col && column + 1 < max_cols && (force || (column_height > 0.0 && current_y + pitch(false) > column_height + 1e-9)) {
column += 1; column += 1;
@@ -817,73 +761,8 @@ mod tests {
assert_eq!(pp.tabs, vec![(2.0, TabKind::Left), (4.0, TabKind::Center), (6.0, TabKind::Right), (8.0, TabKind::Decimal)]); assert_eq!(pp.tabs, vec![(2.0, TabKind::Left), (4.0, TabKind::Center), (6.0, TabKind::Right), (8.0, TabKind::Decimal)]);
assert_eq!(pp.align, ParaAlign::Center); assert_eq!(pp.align, ParaAlign::Center);
assert!((pp.before - 0.5).abs() < f64::EPSILON); assert!((pp.before - 0.5).abs() < f64::EPSILON);
assert_eq!(pp.line_spacing, None);
pp.apply("sm1.5,sb0.25,sa0.75");
assert_eq!(pp.line_spacing, Some(ParaLineSpacing::Multiple(1.5)));
assert!((pp.before - 0.25).abs() < f64::EPSILON);
assert!((pp.after - 0.75).abs() < f64::EPSILON);
let mut back = ParaProps::default(); let mut back = ParaProps::default();
back.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';')); back.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';'));
assert_eq!(back, pp); assert_eq!(back, pp);
for (code, expected) in [
("se1.25", Some(ParaLineSpacing::Exact(1.25))),
("sd0.8", Some(ParaLineSpacing::AtLeast(0.8))),
("sm2x", Some(ParaLineSpacing::Multiple(2.0))),
("s*", None),
] {
pp.apply(code);
assert_eq!(pp.line_spacing, expected, "{code}");
let mut round = ParaProps::default();
round.apply(pp.code().trim_start_matches("\\p").trim_end_matches(';'));
assert_eq!(round, pp, "{code}");
}
}
#[test]
fn paragraph_line_spacing_overrides_entity_factor() {
let p_08 = MTextParams { line_spacing: 0.8, line_spacing_exact: false, ..MTextParams::new(Vec2::ZERO, 0.2) };
let p_10 = MTextParams { line_spacing: 1.0, line_spacing_exact: false, ..MTextParams::new(Vec2::ZERO, 0.2) };
let overridden = super::super::layout_mtext_with("\\pxsm1;{AAA ONE\\PBBB TWO\\PCCC THREE}", &p_08);
let reference = super::super::layout_mtext_with("{AAA ONE\\PBBB TWO\\PCCC THREE}", &p_10);
assert!(
overridden.bounds.min.dist(reference.bounds.min) < 1e-9 && overridden.bounds.max.dist(reference.bounds.max) < 1e-9,
"bounds {:?} vs {:?}",
overridden.bounds,
reference.bounds
);
assert_eq!(overridden.strokes.len(), reference.strokes.len());
for (a, b) in overridden.strokes.iter().flatten().zip(reference.strokes.iter().flatten()) {
assert!(a.dist(*b) < 1e-9, "{a:?} vs {b:?}");
}
// Exact mode keeps fixed pitch even over a taller inline character; Multiple and AtLeast expand.
let p_exact = MTextParams { line_spacing: 1.0, line_spacing_exact: true, ..MTextParams::new(Vec2::ZERO, 0.2) };
let exact_para = super::super::layout_mtext_with("\\pxse1;A\\P{\\H2x;B}\\PC", &p_08);
let exact_ref = super::super::layout_mtext_with("A\\P{\\H2x;B}\\PC", &p_exact);
assert!(exact_para.bounds.min.dist(exact_ref.bounds.min) < 1e-9);
let at_least_para = super::super::layout_mtext_with("\\pxsd1;A\\P{\\H2x;B}\\PC", &p_08);
assert!(at_least_para.bounds.height() > exact_para.bounds.height() + 0.1);
// AtLeast floors step height at entity height when inline runs are shorter; Multiple scales down.
let at_least_short = super::super::layout_mtext_with("\\pxsd1;A\\P{\\H0.5x;B}\\PC", &p_08);
let multiple_short = super::super::layout_mtext_with("\\pxsm1;A\\P{\\H0.5x;B}\\PC", &p_08);
let at_least_plain = super::super::layout_mtext_with("\\pxsd1;A\\PB\\PC", &p_08);
assert!((at_least_short.bounds.height() - at_least_plain.bounds.height()).abs() < 1e-9);
assert!(multiple_short.bounds.height() < at_least_short.bounds.height() - 0.05);
// `\pxs*;` reverts to the entity's line spacing factor for subsequent paragraphs.
let reset = super::super::layout_mtext_with("\\pxsm1;A\\PB\\P\\pxs*;C", &p_08);
let all_one = super::super::layout_mtext_with("\\pxsm1;A\\PB\\PC", &p_08);
assert!(reset.bounds.height() < all_one.bounds.height() - 0.05);
// `code_after` emits explicit resets (`s*`, `b0`, `a0`) when dropping overrides from `prev`.
let mut prev = ParaProps::default();
prev.apply("sm1.5,sb0.25,sa0.75");
let default = ParaProps::default();
let reset_code = default.code_after(&prev);
let mut applied = prev.clone();
applied.apply(reset_code.trim_start_matches("\\p").trim_end_matches(';'));
assert_eq!(applied, default, "reset code: {reset_code}");
} }
} }
+7 -79
View File
@@ -89,17 +89,12 @@ impl Face {
self.font().is_some_and(|f| f.charmap().map(c).is_some()) self.font().is_some_and(|f| f.charmap().map(c).is_some())
} }
/// The family name, as the font gives it (the typographic family, else the family when that /// The family name, as the font gives it (the typographic family, else the family when that
/// is missing or blank). A record that reads as blank (empty, or in an encoding that is not /// is missing or blank).
/// decoded, such as a Mac name in Shift-JIS) is passed over for the next one with the same id.
pub fn family_name(&self) -> Option<String> { pub fn family_name(&self) -> Option<String> {
let f = self.font()?; let f = self.font()?;
[skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME].into_iter().find_map(|id| { [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME].into_iter().find_map(|id| {
// At most MAX_NAME_RECORDS records per id, each read up to MAX_NAME_CHARS characters, let s = f.localized_strings(id).next()?.to_string();
// as in `names`. Some(s.chars().filter(|c| !c.is_control()).take(80).collect::<String>()).filter(|s| !s.trim().is_empty())
f.localized_strings(id).take(MAX_NAME_RECORDS).find_map(|s| {
let s = s.chars().take(MAX_NAME_CHARS).filter(|c| !c.is_control()).take(80).collect::<String>();
(!s.trim().is_empty()).then_some(s)
})
}) })
} }
/// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the /// How tall the glyph of `c` is, from its lowest to its highest point, in ems: `None` when the
@@ -1555,86 +1550,19 @@ mod family_tests {
assert!(available(crate::BUILTIN_FONT)); assert!(available(crate::BUILTIN_FONT));
} }
/// A `name` table record: platform, encoding, language, name id, the string's bytes as stored.
type Record = (u16, u16, u16, u16, Vec<u8>);
/// A font file holding only a `name` table with `records`, which is all reading names parses.
fn font_with_names(records: &[Record]) -> Vec<u8> {
let count = u16::try_from(records.len()).unwrap();
let mut name: Vec<u8> = [0, count, 6 + 12 * count].into_iter().flat_map(u16::to_be_bytes).collect();
let mut strings = Vec::new();
for (platform, encoding, language, id, text) in records {
let (len, offset) = (u16::try_from(text.len()).unwrap(), u16::try_from(strings.len()).unwrap());
name.extend([*platform, *encoding, *language, *id, len, offset].into_iter().flat_map(u16::to_be_bytes));
strings.extend_from_slice(text);
}
name.extend(strings);
// TrueType table directory with one table record; the table follows at byte 28.
let mut font = 0x0001_0000u32.to_be_bytes().to_vec();
font.extend([1u16, 16, 0, 0].into_iter().flat_map(u16::to_be_bytes));
font.extend(b"name");
font.extend([0, 28, u32::try_from(name.len()).unwrap()].into_iter().flat_map(u32::to_be_bytes));
font.extend(name);
font
}
fn utf16(s: &str) -> Vec<u8> {
s.encode_utf16().flat_map(u16::to_be_bytes).collect()
}
/// Reading a user font's names for a list keeps none of its bytes and uses none of the load /// Reading a user font's names for a list keeps none of its bytes and uses none of the load
/// budget. The font file is written here, so the check does not depend on which fonts are /// budget. (Font folders themselves are process-wide: `tests/ttf_font_folders.rs`.)
/// installed. (Font folders themselves are process-wide: `tests/ttf_font_folders.rs`.)
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
#[test] #[test]
fn reading_a_user_fonts_names_keeps_no_font_bytes() { fn reading_a_user_fonts_names_keeps_no_font_bytes() {
/// A folder of this test's own, made here so nothing else put it there first, and removed let Some(src) = scan().into_values().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("ttf"))) else { return };
/// with the font in it when the test ends, also when it fails.
struct TestDir(std::path::PathBuf);
impl Drop for TestDir {
/// Removes the folder and all it holds.
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let mut attempt = 0u32;
let dir = loop {
let dir = std::env::temp_dir().join(format!("cadcraft-face-names-{}-{attempt}", std::process::id()));
match std::fs::create_dir(&dir) {
Ok(()) => break TestDir(dir),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => attempt += 1,
Err(e) => panic!("{}: {e}", dir.display()),
}
};
let path = dir.0.join("face.ttf");
std::fs::write(&path, font_with_names(&[(3, 1, 0x409, 1, utf16("Face Family"))])).unwrap();
let mut db = Db::default(); let mut db = Db::default();
db.user.insert("face".into()); db.user.insert("face".into());
db.paths.insert("face".into(), Source::File(path)); db.paths.insert("face".into(), Source::File(src));
let family = db.face_names("face").and_then(|n| n.family.clone()); assert!(db.face_names("face").is_some_and(|n| n.family.is_some()));
assert_eq!(family.as_deref(), Some("Face Family"), "the names are read from the file");
assert!(db.files.is_empty() && db.loaded_bytes == 0); assert!(db.files.is_empty() && db.loaded_bytes == 0);
} }
/// A family name is read past name records that read as blank: an empty Unicode-platform
/// record before the Mac and Windows names (the shape of some installed fonts), or a Mac name
/// in Shift-JIS, which is not decoded.
#[test]
fn a_family_name_is_read_past_blank_name_records() {
let family = |records: &[Record]| faces(&Arc::new(font_with_names(records))).first().and_then(Face::family_name);
let empty = (0, 0, 0, 1, Vec::new());
let mac = (1, 0, 0, 1, b"Face Family".to_vec());
let windows = (3, 1, 0x409, 1, utf16("Face Family"));
assert_eq!(family(&[empty.clone(), mac, windows.clone()]).as_deref(), Some("Face Family"));
// Fullwidth "MS" in Shift-JIS: Mac platform 1, Japanese encoding 1, language 11.
let sjis = |id| (1, 1, 11, id, vec![0x82, 0x6C, 0x82, 0x72]);
assert_eq!(family(&[sjis(1), windows]).as_deref(), Some("Face Family"));
// The typographic family still comes first when its first record reads as blank.
let typographic = [empty.clone(), sjis(16), (3, 1, 0x409, 1, utf16("Face")), (3, 1, 0x409, 16, utf16("Face Family"))];
assert_eq!(family(&typographic).as_deref(), Some("Face Family"));
assert_eq!(family(&[empty, (1, 0, 0, 1, b" ".to_vec()), sjis(1)]), None, "no name that can be read");
}
/// One unreadable user font file with the family does not stop the search: the next file /// One unreadable user font file with the family does not stop the search: the next file
/// that has the family is still read. /// that has the family is still read.
#[test] #[test]
-30
View File
@@ -81,36 +81,6 @@ impl Spline {
speed > 0.0 && d0.near(d1, 1e-9 * speed) && self.eval(lo).near(self.eval(hi), 1e-9 * speed * (hi - lo)) speed > 0.0 && d0.near(d1, 1e-9 * speed) && self.eval(lo).near(self.eval(hi), 1e-9 * speed * (hi - lo))
} }
/// The number of distinct control points: control points that wrap round repeat their first
/// `degree` at the end, and a clamped closed spline repeats its first at the end. Only points
/// that really repeat count: with wrapping knots but a different tail, every control point is
/// its own, even when only the last repeats the first.
pub fn distinct_controls(&self) -> usize {
let n = self.control.len();
let u = n.saturating_sub(self.degree);
let tail_repeats = || u > 0 && self.control.iter().zip(self.control.iter().skip(u)).all(|(a, b)| a.near(*b, 1e-12));
if self.wraps() && tail_repeats() {
u
} else if self.closed && !self.wraps() && n > 2 && self.control.first().zip(self.control.last()).is_some_and(|(a, b)| a.near(*b, 1e-12)) {
n - 1
} else {
n
}
}
/// Indices holding distinct control point `j` (with its repeats).
pub fn control_copies(&self, j: usize) -> Vec<usize> {
let (n, u) = (self.control.len(), self.distinct_controls());
if j >= u {
return Vec::new();
}
let mut out = vec![j];
if u < n {
out.extend((j + u..n).step_by(u.max(1)));
}
out
}
pub fn is_valid(&self) -> bool { pub fn is_valid(&self) -> bool {
let n = self.control.len(); let n = self.control.len();
n > self.degree n > self.degree
-33
View File
@@ -603,36 +603,3 @@ fn the_cyclic_matrix_of_a_closed_fit_keeps_the_full_sweep() {
assert_same_solution(&a, &b, &format!("cyclic n={n}")); assert_same_solution(&a, &b, &format!("cyclic n={n}"));
} }
} }
/// Control points count as copies only where they repeat: a closed spline whose knots wrap but
/// whose last control points don't repeat the first ones keeps every control point its own.
#[test]
fn only_repeated_control_points_are_copies() {
let v = Vec2::new;
let square = [v(0.0, 0.0), v(4.0, 0.0), v(4.0, 4.0), v(0.0, 4.0)];
let wraps = Spline {
degree: 2,
knots: (0..9).map(f64::from).collect(),
control: square.iter().chain(&square[..2]).copied().collect(),
closed: true,
..Spline::default()
};
assert!(wraps.wraps() && wraps.distinct_controls() < wraps.control.len());
assert_eq!(wraps.control_copies(0), [0, 4]);
let tail = Spline {
degree: 2,
knots: vec![0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0],
control: square.iter().copied().chain([v(2.0, 0.0)]).collect(),
closed: true,
..Spline::default()
};
assert!(tail.is_valid() && tail.wraps());
assert_eq!(tail.distinct_controls(), tail.control.len());
assert_eq!(tail.control_copies(0), [0]);
let first_again = Spline { control: square.iter().copied().chain([v(0.0, 0.0)]).collect(), ..tail };
assert!(first_again.is_valid() && first_again.wraps());
assert_eq!(first_again.distinct_controls(), first_again.control.len());
assert_eq!(first_again.control_copies(0), [0]);
}
+2 -13
View File
@@ -86,18 +86,7 @@ pub(super) fn hatch(tags: &[Tag], t: &T, curves: &mut CurvePoints) -> Option<Ent
// Keep the file's definition lines even for a name the library knows: the library's versions // Keep the file's definition lines even for a name the library knows: the library's versions
// of some patterns (AR-CONC) only approximate AutoCAD's, and drawing them at the file's scale // of some patterns (AR-CONC) only approximate AutoCAD's, and drawing them at the file's scale
// could be hundreds of times denser than the hatch the author saw. // could be hundreds of times denser than the hatch the author saw.
let pattern_lines = if solid { let pattern_lines = if solid { Vec::new() } else { pattern_definition(tags, scale, angle, origin) };
Vec::new()
} else {
let lines = pattern_definition(tags, scale, angle, origin);
// A file that lists no definition lines for a user-defined hatch (AutoCAD writes its own
// with 78 = 0) means its angle, spacing and double flag; build the families from those.
if lines.is_empty() && cadcraft_doc::library::is_user_pattern(&pattern) {
cadcraft_doc::library::user_defined_lines(t.i(77).unwrap_or(0) != 0)
} else {
lines
}
};
Some(EntityKind::Hatch(Hatch { Some(EntityKind::Hatch(Hatch {
pattern: pattern.to_ascii_uppercase(), pattern: pattern.to_ascii_uppercase(),
solid, solid,
@@ -344,7 +333,7 @@ const MAX_PATTERN_DASHES: usize = 256;
/// non-finite values are skipped. /// non-finite values are skipped.
fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec<cadcraft_doc::library::PatternLine> { fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec<cadcraft_doc::library::PatternLine> {
let Some(at) = tags.iter().position(|x| x.code == 78) else { return Vec::new() }; let Some(at) = tags.iter().position(|x| x.code == 78) else { return Vec::new() };
let scale = cadcraft_doc::library::effective_hatch_pattern_scale(scale); let scale = if scale.is_finite() && scale > 1e-9 { scale } else { 1.0 };
let angle = if angle.is_finite() { angle } else { 0.0 }; let angle = if angle.is_finite() { angle } else { 0.0 };
// Raw lines: angle (degrees), base, offset, dashes. // Raw lines: angle (degrees), base, offset, dashes.
let mut raw: Vec<(f64, Vec2, Vec2, Vec<f64>)> = Vec::new(); let mut raw: Vec<(f64, Vec2, Vec2, Vec<f64>)> = Vec::new();
+7 -28
View File
@@ -444,18 +444,8 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper
DimKind::ArcLength => 1, DimKind::ArcLength => 1,
}; };
w.i(70, ty | 32 | if dm.user_text_pos { 128 } else { 0 }); w.i(70, ty | 32 | if dm.user_text_pos { 128 } else { 0 });
// The actual measurement (read-only in DXF): AutoLISP's entget shows it. Linear // The actual measurement (read-only in DXF): AutoLISP's entget shows it.
// measurements carry DIMLFAC; angles are radians. A negative factor means 1.0 in model w.f(42, g.measurement);
// space and its absolute value in paper space (Autodesk's model/paper-space rule).
let measurement = match dm.kind {
DimKind::Angular | DimKind::Angular3P => g.measurement,
_ => {
let factor = style.with_overrides(&dm.overrides).linear_factor;
let factor = if factor < 0.0 { if paper { factor.abs() } else { 1.0 } } else { factor };
g.measurement * factor
}
};
w.f(42, measurement);
if !dm.text.is_empty() { if !dm.text.is_empty() {
w.s(1, crate::dxf_read::mtext_dxf::encode_line(&dm.text)); w.s(1, crate::dxf_read::mtext_dxf::encode_line(&dm.text));
} }
@@ -694,44 +684,33 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
} }
} }
w.i(75, i64::from(h.style)); w.i(75, i64::from(h.style));
// Pattern type: 0 for a user-defined hatch (its lines come from its angle, spacing and w.i(76, 1);
// double flag, groups 52, 41 and 77); 1 for a predefined (library) pattern.
let user = cadcraft_doc::library::is_user_pattern(&h.pattern);
w.i(76, if user { 0 } else { 1 });
// Angle, scale and double flag are a pattern fill's: AutoCAD 2024 writes none of them on a // Angle, scale and double flag are a pattern fill's: AutoCAD 2024 writes none of them on a
// solid or gradient fill, and refuses a file whose solid HATCH has any of them ("Error: // solid or gradient fill, and refuses a file whose solid HATCH has any of them ("Error:
// expected group code 98", the whole drawing discarded; measured). // expected group code 98", the whole drawing discarded; measured).
if !h.solid { if !h.solid {
w.f(52, h.angle.to_degrees()); w.f(52, h.angle.to_degrees());
w.f(41, h.scale); w.f(41, h.scale);
w.i(77, 0);
// The lines read from the file, else the library's pattern of that name. // The lines read from the file, else the library's pattern of that name.
let lines = if h.pattern_lines.is_empty() { let lines = if h.pattern_lines.is_empty() {
cadcraft_doc::library::pattern_for(d, &h.pattern).map(|p| p.lines).unwrap_or_default() cadcraft_doc::library::pattern_for(d, &h.pattern).map(|p| p.lines).unwrap_or_default()
} else { } else {
h.pattern_lines.clone() h.pattern_lines.clone()
}; };
// Double hatch area (group 77): a user-defined hatch's second family, at right angles.
w.i(77, i64::from(user && lines.len() > 1));
// The number of pattern definition lines, then each line's angle, base point, offset
// and dashes, scaled and rotated as the hatch draws them. The DXF Reference has no
// user-defined exception: its families are listed here as any pattern's are, and a
// reader given 78 = 0 has no lines to draw.
w.i(78, lines.len() as i64); w.i(78, lines.len() as i64);
// The scale the renderer and the reader use: one too small to draw is 1, so a resave
// writes the lines it read back.
let k = cadcraft_doc::library::effective_hatch_pattern_scale(h.scale);
for pl in lines { for pl in lines {
let ang = pl.angle.to_radians() + h.angle; let ang = pl.angle.to_radians() + h.angle;
w.f(53, ang.to_degrees()); w.f(53, ang.to_degrees());
let o = h.origin + Vec2::new(pl.origin.0, pl.origin.1).rotate(h.angle) * k; let o = h.origin + Vec2::new(pl.origin.0, pl.origin.1).rotate(h.angle) * h.scale;
w.f(43, o.x); w.f(43, o.x);
w.f(44, o.y); w.f(44, o.y);
let dl = Vec2::new(pl.delta.0, pl.delta.1).rotate(ang) * k; let dl = Vec2::new(pl.delta.0, pl.delta.1).rotate(ang) * h.scale;
w.f(45, dl.x); w.f(45, dl.x);
w.f(46, dl.y); w.f(46, dl.y);
w.i(79, pl.dashes.len() as i64); w.i(79, pl.dashes.len() as i64);
for dsh in pl.dashes { for dsh in pl.dashes {
w.f(49, dsh * k); w.f(49, dsh * h.scale);
} }
} }
} }
-88
View File
@@ -241,94 +241,6 @@ fn justified_text_made_here_writes_its_baseline_start_for_every_justification()
assert_eq!(text_starts(&write_dxf(&back)), starts); assert_eq!(text_starts(&write_dxf(&back)), starts);
} }
fn with_linear_factor(mut d: Drawing, factor: f64) -> Drawing {
d.dim_styles.last_mut().expect("S25").linear_factor = factor;
d
}
#[test]
fn stored_linear_measurements_include_dimlfac_but_angles_stay_in_radians() {
let linear_case = with_linear_factor(linear(0.0), 100.0);
assert!((stored_measurement(&linear_case) - 10000.0).abs() < 1e-7, "linear and its DIMLFAC=100 style");
let aligned = with_linear_factor(s25(DimKind::Aligned, Vec3::ZERO, Vec3::new(3.0, 4.0, 0.0), Vec3::new(0.0, -5.0, 0.0)), 100.0);
assert!((stored_measurement(&aligned) - 500.0).abs() < 1e-7, "aligned");
let radius = with_linear_factor(s25(DimKind::Radius, Vec3::ZERO, Vec3::ZERO, Vec3::ZERO), 100.0);
let radius = {
let mut d = radius;
let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle;
d.modify_entity(h, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.p15 = Vec3::new(2.5, 0.0, 0.0);
}
})
.unwrap();
d
};
assert!((stored_measurement(&radius) - 250.0).abs() < 1e-7, "radius");
let diameter = with_linear_factor(s25(DimKind::Diameter, Vec3::ZERO, Vec3::ZERO, Vec3::ZERO), 100.0);
let diameter = {
let mut d = diameter;
let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle;
d.modify_entity(h, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.p15 = Vec3::new(5.0, 0.0, 0.0);
}
})
.unwrap();
d
};
assert!((stored_measurement(&diameter) - 500.0).abs() < 1e-7, "diameter");
let ordinate = with_linear_factor(s25(DimKind::Ordinate { x_type: true }, Vec3::new(4.0, 0.0, 0.0), Vec3::new(5.0, 1.0, 0.0), Vec3::ZERO), 100.0);
let ordinate_measurement = stored_measurement_dxf(&ordinate);
assert!((ordinate_measurement - 400.0).abs() < 1e-7, "ordinate: {ordinate_measurement}");
let arc = with_linear_factor(
s25(
DimKind::ArcLength,
Vec3::new(2.0, 0.0, 0.0),
Vec3::new(0.0, 2.0, 0.0),
Vec3::new(std::f64::consts::SQRT_2, std::f64::consts::SQRT_2, 0.0),
),
100.0,
);
assert!((stored_measurement_dxf(&arc) - std::f64::consts::PI * 100.0).abs() < 1e-7, "arc length");
let overridden = with_linear_factor(linear(0.0), 100.0);
let overridden = {
let mut d = overridden;
let h = d.model.iter().find(|e| matches!(e.kind, EntityKind::Dimension(_))).unwrap().handle;
d.modify_entity(h, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.overrides.insert("DIMLFAC".into(), serde_json::json!(2.0));
}
})
.unwrap();
d
};
assert!((stored_measurement(&overridden) - 200.0).abs() < 1e-9, "a dimension's own DIMLFAC override wins");
let angular = with_linear_factor(s25(DimKind::Angular3P, polar(0.0, 20.0), polar(90.0, 20.0), polar(45.0, 15.0)), 100.0);
assert!((stored_measurement(&angular) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "DIMLFAC never scales an angle");
let control = with_linear_factor(linear(0.0), 1.0);
assert!((stored_measurement(&control) - 100.0).abs() < 1e-9, "DIMLFAC=1 keeps the raw measurement");
}
#[test]
fn negative_dimlfac_follows_the_dimension_space() {
let model = with_linear_factor(linear(0.0), -2.0);
assert!((stored_measurement(&model) - 100.0).abs() < 1e-9, "model space uses 1.0 when DIMLFAC is negative");
let entity = model.model.iter().next().expect("the linear dimension");
let mut paper = Drawing::new_metric();
paper.dim_styles = model.dim_styles.clone();
paper.add(&Space::Paper("Layout1".into()), entity.common.clone(), entity.kind.clone()).unwrap();
assert!((stored_measurement(&paper) - 200.0).abs() < 1e-9, "paper space uses the absolute DIMLFAC");
}
/// Group 42 in CADCraft's direct DXF output.
fn stored_measurement_dxf(d: &Drawing) -> f64 {
let t = tags(&write_dxf(d));
let dim = t.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap();
t[dim..].iter().find(|(c, _)| *c == 42).unwrap().1.parse().unwrap()
}
/// Group 42 of a dimension in the DXF AutoCAD reads from `d`'s DWG. /// Group 42 of a dimension in the DXF AutoCAD reads from `d`'s DWG.
fn stored_measurement(d: &Drawing) -> f64 { fn stored_measurement(d: &Drawing) -> f64 {
cadcraft_io::dwg_worker::allow_in_process(); cadcraft_io::dwg_worker::allow_in_process();
+6 -127
View File
@@ -1,6 +1,5 @@
//! HATCH pattern definition lines (groups 78, 53, 43–46, 79, 49) survive a DXF read and save: a //! HATCH pattern definition lines (groups 78, 53, 43–46, 79, 49) of a pattern the library
//! pattern the library doesn't define (issue #290), and a user-defined hatch's own families, which //! doesn't define survive a DXF read and save (issue #290).
//! a DWG keeps too.
use cadcraft_doc::library::PatternLine; use cadcraft_doc::library::PatternLine;
use cadcraft_doc::*; use cadcraft_doc::*;
@@ -36,22 +35,15 @@ fn custom_lines() -> Vec<PatternLine> {
] ]
} }
fn drawing(h: Hatch) -> Drawing { fn save(h: Hatch) -> String {
let mut d = Drawing::new_imperial(); let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).expect("add"); d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).expect("add");
d write_dxf(&d)
}
fn save(h: Hatch) -> String {
write_dxf(&drawing(h))
}
fn first_hatch_of(d: &Drawing) -> Hatch {
d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).expect("hatch")
} }
fn first_hatch(text: &str) -> Hatch { fn first_hatch(text: &str) -> Hatch {
first_hatch_of(&read_dxf(text.as_bytes()).expect("read")) let d = read_dxf(text.as_bytes()).expect("read");
d.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).expect("hatch")
} }
/// (group code, value) pairs of a DXF text. /// (group code, value) pairs of a DXF text.
@@ -66,12 +58,6 @@ fn pattern_data(p: &[(i32, String)]) -> usize {
p.iter().skip(hatch).position(|(c, _)| *c == 78).map(|k| hatch + k).expect("78") p.iter().skip(hatch).position(|(c, _)| *c == 78).map(|k| hatch + k).expect("78")
} }
/// The first value of group `code` in the first HATCH of a DXF text.
fn hatch_group(p: &[(i32, String)], code: i32) -> Option<String> {
let hatch = p.iter().position(|(c, v)| *c == 0 && v == "HATCH")?;
p.iter().skip(hatch).find(|(c, _)| *c == code).map(|(_, v)| v.clone())
}
fn join(p: &[(i32, String)]) -> String { fn join(p: &[(i32, String)]) -> String {
p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
} }
@@ -111,99 +97,6 @@ fn custom_pattern_lines_roundtrip_scaled_and_rotated() {
assert!(near(&first_hatch(&save(h)).pattern_lines, &custom_lines())); assert!(near(&first_hatch(&save(h)).pattern_lines, &custom_lines()));
} }
#[test]
fn user_defined_hatches_save_their_type_double_flag_and_lines_and_read_back() {
let lines = cadcraft_doc::library::user_defined_lines(true);
let text = save(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 30f64.to_radians(), Vec2::new(1.0, 2.0), lines.clone()));
let p = pairs(&text);
assert_eq!(hatch_group(&p, 2).as_deref(), Some("_USER"));
assert_eq!(hatch_group(&p, 76).as_deref(), Some("0"), "pattern type 0: user-defined");
assert_eq!(hatch_group(&p, 77).as_deref(), Some("1"), "double hatch area");
assert_eq!(hatch_group(&p, 78).as_deref(), Some("2"), "the two families are listed");
// Each family is written as a pattern line is: its angle, base point, offset and dashes.
let at = pattern_data(&p);
let num = |k: usize| p[at + k].1.parse::<f64>().expect("number");
let off = Vec2::new(0.0, 1.0).rotate(30f64.to_radians()) * 2.0;
assert!((num(1) - 30.0).abs() < 1e-9, "53 angle: the family turned by the hatch's angle");
assert!((num(2) - 1.0).abs() < 1e-9 && (num(3) - 2.0).abs() < 1e-9, "43/44 base point at the hatch origin");
assert!((num(4) - off.x).abs() < 1e-9 && (num(5) - off.y).abs() < 1e-9, "45/46 offset: the spacing, turned");
assert_eq!(p[at + 6], (79, "0".into()), "79 dashes");
// Read back to the same angle, spacing and families, and saved again unchanged.
let h = first_hatch(&text);
assert_eq!(h.pattern, "_USER");
assert!((h.scale - 2.0).abs() < 1e-12 && (h.angle - 30f64.to_radians()).abs() < 1e-12, "{} {}", h.scale, h.angle);
assert!(near(&h.pattern_lines, &lines), "{:?}", h.pattern_lines);
assert!(near(&first_hatch(&save(h)).pattern_lines, &lines));
// One family is not doubled, and a predefined pattern is type 1 with its lines listed.
let single = save(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 0.0, Vec2::ZERO, cadcraft_doc::library::user_defined_lines(false)));
let p = pairs(&single);
assert_eq!(hatch_group(&p, 76).as_deref(), Some("0"));
assert_eq!(hatch_group(&p, 77).as_deref(), Some("0"));
assert_eq!(hatch_group(&p, 78).as_deref(), Some("1"), "the one family is listed");
assert_eq!(first_hatch(&single).pattern_lines.len(), 1);
let ansi = save(hatch("ANSI31", 1.0, 0.0, Vec2::ZERO, custom_lines()));
let p = pairs(&ansi);
assert_eq!(hatch_group(&p, 76).as_deref(), Some("1"));
assert_eq!(hatch_group(&p, 77).as_deref(), Some("0"));
assert_eq!(hatch_group(&p, 78).as_deref(), Some("2"));
}
/// A user-defined hatch's families are a pattern definition like any other's, so an imported one
/// based away from its origin and doubled keeps both families' angle, base point, offset and count
/// through a DXF save and a DWG save. Written as 78 = 0 they were lost: a reader with no fallback
/// drew nothing, and this program's fallback moved the base point to the hatch's origin.
#[test]
fn a_user_defined_hatch_keeps_its_line_definitions_through_dxf_and_dwg() {
// Two families based at (1,1): a double hatch whose lines do not start at its origin.
let mut lines = cadcraft_doc::library::user_defined_lines(true);
for l in &mut lines {
l.origin = (1.0, 1.0);
}
let d = drawing(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 30f64.to_radians(), Vec2::ZERO, lines.clone()));
let text = write_dxf(&d);
assert_eq!(hatch_group(&pairs(&text), 78).as_deref(), Some("2"), "the file lists both families");
let back = first_hatch(&text);
assert_eq!(back.pattern_lines.len(), 2, "{:?}", back.pattern_lines);
assert!(near(&back.pattern_lines, &lines), "{:?}", back.pattern_lines);
// A DWG keeps them too: the DWG bridge converts the same written HATCH.
#[cfg(not(target_arch = "wasm32"))]
{
cadcraft_io::dwg_worker::allow_in_process();
let dwg = cadcraft_io::write(&d, "user-pattern.dwg").expect("write dwg");
let h = first_hatch_of(&cadcraft_io::read(&dwg, "user-pattern.dwg").expect("read dwg"));
assert_eq!(h.pattern_lines.len(), 2, "{:?}", h.pattern_lines);
assert!(near(&h.pattern_lines, &lines), "{:?}", h.pattern_lines);
}
}
/// A user-defined hatch a file lists with 78 = 0 (AutoCAD writes its own so) has no definition
/// lines: the reader makes its families from the double flag (77), and keeps the hatch's angle
/// (52) and spacing (41) to turn and space them.
#[test]
fn a_user_defined_hatch_listing_no_lines_gets_its_families_from_the_double_flag() {
let lines = cadcraft_doc::library::user_defined_lines(false);
let text = save(hatch(cadcraft_doc::library::USER_PATTERN, 2.0, 30f64.to_radians(), Vec2::new(1.0, 2.0), lines));
let p = pairs(&text);
let at = pattern_data(&p);
let end = p.iter().skip(at).position(|(c, _)| *c == 98).map(|k| at + k).expect("98");
for double in [false, true] {
// The hatch as such a file has it: its double flag, then 78 = 0 and no lines.
let mut q = p.clone();
q.splice(at..end, [(78, "0".to_string())]);
let flag = q[..at].iter().rposition(|(c, _)| *c == 77).expect("77");
q[flag].1 = u8::from(double).to_string();
assert_eq!(hatch_group(&q, 78).as_deref(), Some("0"));
assert_eq!(hatch_group(&q, 53), None, "no definition line is left in the file");
let h = first_hatch(&join(&q));
assert_eq!(h.pattern, cadcraft_doc::library::USER_PATTERN);
assert!((h.scale - 2.0).abs() < 1e-12 && (h.angle - 30f64.to_radians()).abs() < 1e-12, "{} {}", h.scale, h.angle);
assert_eq!(h.pattern_lines.len(), if double { 2 } else { 1 }, "double = {double}: {:?}", h.pattern_lines);
assert!(near(&h.pattern_lines, &cadcraft_doc::library::user_defined_lines(double)), "double = {double}: {:?}", h.pattern_lines);
}
}
#[test] #[test]
fn library_named_patterns_keep_the_files_definition() { fn library_named_patterns_keep_the_files_definition() {
// The library's AR-CONC only approximates AutoCAD's: the file's own lines are kept and saved. // The library's AR-CONC only approximates AutoCAD's: the file's own lines are kept and saved.
@@ -253,17 +146,3 @@ fn hostile_pattern_definitions_are_capped() {
d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).expect("add"); d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).expect("add");
let _ = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default()); let _ = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default());
} }
#[test]
fn a_hatch_too_small_to_scale_saves_the_same_lines_each_time() {
// A spacing at or below 1e-9 is drawn and read at unit scale; the writer uses the same scale,
// so saving again does not shrink the lines.
let lines = cadcraft_doc::library::user_defined_lines(false);
let d = drawing(hatch(cadcraft_doc::library::USER_PATTERN, 1e-9, 0.0, Vec2::ZERO, lines));
let once = first_hatch(&write_dxf(&d));
let twice = first_hatch(&write_dxf(&drawing(once.clone())));
// Compared as a ratio: the values are far below any fixed tolerance.
let spacing = |h: &Hatch| h.pattern_lines.first().map(|l| l.delta.1).unwrap_or(f64::NAN);
let ratio = spacing(&twice) / spacing(&once);
assert!((ratio - 1.0).abs() < 1e-6, "{:?} then {:?}", once.pattern_lines, twice.pattern_lines);
}
-2
View File
@@ -39,8 +39,6 @@ pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) {
explodable, explodable,
units, units,
array, array,
// Session state (when an xref was read), never in a file.
xref_stamp: _,
} = block.as_ref(); } = block.as_ref();
equal(name, &back.name, &path, "name"); equal(name, &back.name, &path, "name");
equal(annotative, &back.annotative, &path, "annotative"); equal(annotative, &back.annotative, &path, "annotative");
+7 -12
View File
@@ -398,16 +398,14 @@ impl Headless {
s.execute(&id, &params).map_err(|e| e.to_string()) s.execute(&id, &params).map_err(|e| e.to_string())
} }
"cmdline.input" => { "cmdline.input" => {
let before = s.log_mark(); let before = s.log.len();
let r = s.cmdline(&str_p("text").unwrap_or_default()); let r = s.cmdline(&str_p("text").unwrap_or_default());
// No frames here: a LISP routine the line started or answered runs on now.
s.lisp_run_until_input();
// Like the app: a refused line is echoed to the history (and `output`), and also // Like the app: a refused line is echoed to the history (and `output`), and also
// reported in `error`. // reported in `error`.
if let Err(e) = &r { if let Err(e) = &r {
s.echo(e.to_string()); s.echo(e.to_string());
} }
let out: Vec<String> = s.log_since(before).to_vec(); let out: Vec<String> = s.log.iter().skip(before).cloned().collect();
let mut st = state(s); let mut st = state(s);
if let Some(o) = st.as_object_mut() { if let Some(o) = st.as_object_mut() {
o.insert("output".into(), json!(out)); o.insert("output".into(), json!(out));
@@ -418,28 +416,25 @@ impl Headless {
Ok(st) Ok(st)
} }
"cmdline.script" => { "cmdline.script" => {
let before = s.log_mark(); let before = s.log.len();
s.script(&str_p("text").unwrap_or_default()).map_err(|e| e.to_string())?; s.script(&str_p("text").unwrap_or_default()).map_err(|e| e.to_string())?;
let out: Vec<String> = s.log_since(before).to_vec(); let out: Vec<String> = s.log.iter().skip(before).cloned().collect();
Ok(json!({"output": out, "state": state(s)})) Ok(json!({"output": out, "state": state(s)}))
} }
"cmdline.key" => { "cmdline.key" => {
let before = s.log_mark(); let before = s.log.len();
let r = if str_p("key").is_some_and(|k| k.eq_ignore_ascii_case("escape") || k.eq_ignore_ascii_case("esc")) { let r = if str_p("key").is_some_and(|k| k.eq_ignore_ascii_case("escape") || k.eq_ignore_ascii_case("esc")) {
s.cancel(); s.cancel();
Ok(()) Ok(())
} else { } else {
let r = s.input(cadcraft_engine::Input::Enter); s.input(cadcraft_engine::Input::Enter)
// Enter can repeat a LISP command or answer a routine's prompt.
s.lisp_run_until_input();
r
}; };
// Like the app: a refused Enter is echoed to the history (and `output`), and also // Like the app: a refused Enter is echoed to the history (and `output`), and also
// reported in `error`; the call itself succeeds. // reported in `error`; the call itself succeeds.
if let Err(e) = &r { if let Err(e) = &r {
s.echo(e.to_string()); s.echo(e.to_string());
} }
let out: Vec<String> = s.log_since(before).to_vec(); let out: Vec<String> = s.log.iter().skip(before).cloned().collect();
let mut st = state(s); let mut st = state(s);
if let Some(o) = st.as_object_mut() { if let Some(o) = st.as_object_mut() {
o.insert("output".into(), json!(out)); o.insert("output".into(), json!(out));
-62
View File
@@ -78,28 +78,6 @@ fn agent_draws_a_plate_with_holes() {
assert!(img["data"].as_str().unwrap().len() > 100); assert!(img["data"].as_str().unwrap().len() > 100);
} }
/// #3635: headless, nothing gives a LISP routine frames: a long one in a script or typed at the
/// command line runs to its end before the call returns, and the next LISP line runs.
#[test]
fn headless_lisp_routines_run_to_their_end() {
let mut s = Server::new(Box::new(Headless::default()));
let long = "(progn (repeat 1000000 (setq x 1)) (princ \"done\"))";
let lines = |r: &Value| r["output"].as_array().cloned().unwrap_or_default();
let r = tool(&mut s, "script", json!({"text": format!("{long}\n(setq y (+ x 1))\n")}));
assert!(lines(&r).contains(&json!("done")) && r.get("error").is_none(), "{r}");
let r = tool(&mut s, "command_line", json!({"text": long}));
assert!(lines(&r).contains(&json!("done")) && r.get("error").is_none(), "{r}");
let r = tool(&mut s, "command_line", json!({"text": "!y"}));
assert!(lines(&r).contains(&json!("2")), "{r}");
// Enter repeats a LISP command; the control method runs it on as a typed line does.
let mut h = Headless::default();
let mut call = |method: &str, params: Value| crate::Backend::call(&mut h, method, params).unwrap();
call("cmdline.input", json!({"text": format!("(defun c:spin () {long})")}));
assert!(lines(&call("cmdline.input", json!({"text": "spin"}))).contains(&json!("done")));
let r = call("cmdline.key", json!({"key": "enter"}));
assert!(lines(&r).contains(&json!("done")) && r.get("error").is_none(), "{r}");
}
/// Guards that bad input is reported, not fatal: a refused command and a screenshot without a /// Guards that bad input is reported, not fatal: a refused command and a screenshot without a
/// UI are `isError` results, and malformed JSON is a parse error (-32700). /// UI are `isError` results, and malformed JSON is a parse error (-32700).
#[test] #[test]
@@ -512,43 +490,3 @@ fn a_read_root_alone_still_draws_but_writes_nothing() {
let written: Vec<_> = std::fs::read_dir(&outside).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect(); let written: Vec<_> = std::fs::read_dir(&outside).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect();
assert!(written.is_empty(), "nothing is written outside the roots: {written:?}"); assert!(written.is_empty(), "nothing is written outside the roots: {written:?}");
} }
/// #3643: headless, each command-line request reports the lines it printed, also when the command
/// history is trimmed from the front meanwhile.
#[test]
fn headless_output_survives_the_history_trim() {
// Echo lines until the next one trims the history: grow it to its first trim, then back up to
// the length it had just before it.
fn fill(h: &mut Headless) {
let mut top = 0;
loop {
let len = h.session.log.len();
h.session.echo("filler");
if h.session.log.len() < len {
break;
}
top = h.session.log.len();
}
while h.session.log.len() < top {
h.session.echo("filler");
}
}
// The `y` lines a request reports; it reports nothing from before it.
fn ys(h: &mut Headless, method: &str, params: Value) -> usize {
let r = crate::Backend::call(h, method, params).unwrap();
let out = r["output"].as_array().cloned().unwrap_or_default();
assert!(!out.contains(&json!("filler")), "{method}: {r}");
out.iter().filter(|l| *l == "y").count()
}
let mut h = Headless::default();
let lines = "(repeat 20 (princ \"y\") (terpri))";
fill(&mut h);
assert_eq!(ys(&mut h, "cmdline.script", json!({"text": format!("{lines}\n")})), 20);
fill(&mut h);
assert_eq!(ys(&mut h, "cmdline.input", json!({"text": lines})), 20);
// Enter repeats a LISP command that prints them.
ys(&mut h, "cmdline.input", json!({"text": format!("(defun c:ys () {lines} (princ))")}));
ys(&mut h, "cmdline.input", json!({"text": "ys"}));
fill(&mut h);
assert_eq!(ys(&mut h, "cmdline.key", json!({"key": "enter"})), 20);
}
+2 -10
View File
@@ -34,7 +34,6 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
depth: ctx.depth + 1, depth: ctx.depth + 1,
top: ctx.top, top: ctx.top,
frozen: ctx.frozen, frozen: ctx.frozen,
selecting: ctx.selecting,
vp_colors: ctx.vp_colors, vp_colors: ctx.vp_colors,
// The reference's own linetype scale (group 48) multiplies that of the objects inside, // The reference's own linetype scale (group 48) multiplies that of the objects inside,
// as LTSCALE does for the drawing (tests/block_ltscale.rs). // as LTSCALE does for the drawing (tests/block_ltscale.rs).
@@ -113,10 +112,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
b.list.expanded = part.list.expanded; b.list.expanded = part.list.expanded;
b.list.truncated |= part.list.truncated; b.list.truncated |= part.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(part.list.undashed); b.list.undashed = b.list.undashed.saturating_add(part.list.undashed);
let limits = b.limits(); append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) });
if !append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }, limits) {
b.spend();
}
xclip_frame(b, ctx, region, rgb); xclip_frame(b, ctx, region, rgb);
} }
if stop { if stop {
@@ -130,11 +126,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
let mut part = attr_clip.as_ref().map(|_| b.part()); let mut part = attr_clip.as_ref().map(|_| b.part());
attributes(part.as_mut().unwrap_or(&mut *b), ctx, e, ins, rgb, own); attributes(part.as_mut().unwrap_or(&mut *b), ctx, e, ins, rgb, own);
if let (Some(part), Some((region, inverted))) = (part, &attr_clip) { if let (Some(part), Some((region, inverted))) = (part, &attr_clip) {
b.list.truncated |= part.list.truncated; append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) });
let limits = b.limits();
if !append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }, limits) {
b.spend();
}
} }
} }
+106 -241
View File
@@ -53,107 +53,53 @@ pub fn clip_infinite(base: Vec2, dir: Vec2, ray: bool, r: &Bounds2) -> Option<(V
Some((base + dir * t0, base + dir * t1)) Some((base + dir * t0, base + dir * t1))
} }
/// Most a clip may produce: points in all, and pieces (each one primitive). Clipping can cut one
/// primitive into many pieces with more points than it had; a clip within a cap stops at it and
/// says so, so it never builds more than the list it goes into has room for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cap {
pub points: usize,
pub pieces: usize,
}
impl Cap {
/// No cap.
pub const NONE: Cap = Cap { points: usize::MAX, pieces: usize::MAX };
}
/// The pieces of a clipped polyline, built up to a [`Cap`].
struct Pieces {
out: Vec<Vec<Vec2>>,
cur: Vec<Vec2>,
/// The points in `out` and `cur`.
points: usize,
cap: Cap,
/// Whether the cap stopped the pieces.
cut: bool,
}
impl Pieces {
fn new(cap: Cap) -> Pieces {
Pieces { out: Vec::new(), cur: Vec::new(), points: 0, cap, cut: false }
}
/// End the current piece: kept when it has two points or more. (A piece is started only when
/// the cap has room for it, and has fewer points only once the cap refused one, and then
/// nothing more is added.)
fn end(&mut self) {
let cur = std::mem::take(&mut self.cur);
if cur.len() >= 2 {
self.out.push(cur);
}
}
/// Add `p` to the current piece, unless the cap has no room for it (the pieces are then cut).
fn point(&mut self, p: Vec2) {
if self.points >= self.cap.points {
self.cut = true;
} else {
self.points += 1;
self.cur.push(p);
}
}
/// Add the segment `p`→`q`: to the current piece when it starts where that one ends, else as
/// a new piece. With no piece left in the cap, the pieces are cut there: the new piece is not
/// started, so its points are not copied only to be dropped.
fn segment(&mut self, p: Vec2, q: Vec2) {
if !self.cur.last().is_some_and(|l| l.near(p, 1e-12)) {
self.end();
if self.out.len() >= self.cap.pieces {
self.cut = true;
return;
}
self.point(p);
}
self.point(q);
}
/// The pieces, and whether they are all there (the cap did not stop them). Cut pieces are a
/// prefix: the last one may end early.
fn finish(mut self) -> (Vec<Vec<Vec2>>, bool) {
self.end();
(self.out, !self.cut)
}
}
/// Clip a polyline to `r`; returns the visible pieces (each with at least two points). /// Clip a polyline to `r`; returns the visible pieces (each with at least two points).
pub fn clip_polyline(pts: &[Vec2], r: &Bounds2) -> Vec<Vec<Vec2>> { pub fn clip_polyline(pts: &[Vec2], r: &Bounds2) -> Vec<Vec<Vec2>> {
clip_polyline_within(pts, r, Cap::NONE).0 let mut out: Vec<Vec<Vec2>> = Vec::new();
}
/// [`clip_polyline`] within `cap`; false with the pieces when the cap stopped them.
pub fn clip_polyline_within(pts: &[Vec2], r: &Bounds2, cap: Cap) -> (Vec<Vec<Vec2>>, bool) {
if r.is_empty() { if r.is_empty() {
return (Vec::new(), true); return out;
} }
// Fast path: everything inside. // Fast path: everything inside.
if pts.len() <= cap.points && cap.pieces > 0 && pts.iter().all(|p| r.contains(*p)) { if pts.iter().all(|p| r.contains(*p)) {
return (if pts.len() >= 2 { vec![pts.to_vec()] } else { Vec::new() }, true); if pts.len() >= 2 {
} out.push(pts.to_vec());
let mut out = Pieces::new(cap);
for w in pts.windows(2) {
if out.cut {
break;
} }
return out;
}
let mut cur: Vec<Vec2> = Vec::new();
for w in pts.windows(2) {
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue };
match clip_segment(*a, *b, r) { match clip_segment(*a, *b, r) {
Some((p, q)) => { Some((p, q)) => {
out.segment(p, q); let joined = cur.last().is_some_and(|l| l.near(p, 1e-12));
if !joined {
if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
cur.push(p);
}
cur.push(q);
// Leaving the rectangle ends the piece. // Leaving the rectangle ends the piece.
if !q.near(*b, 1e-12) { if !q.near(*b, 1e-12) {
out.end(); if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
} }
} }
None => out.end(), None => {
if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
}
} }
} }
out.finish() if cur.len() >= 2 {
out.push(cur);
}
out
} }
/// Clip a convex polygon to `r` (Sutherland–Hodgman). /// Clip a convex polygon to `r` (Sutherland–Hodgman).
@@ -203,38 +149,22 @@ pub fn clip_polygon(poly: &[Vec2], r: &Bounds2) -> Vec<Vec2> {
/// Clip a triangle list (three vertices per triangle) to `r`, re-triangulating as fans. /// Clip a triangle list (three vertices per triangle) to `r`, re-triangulating as fans.
pub fn clip_triangles(tris: &[Vec2], r: &Bounds2) -> Vec<Vec2> { pub fn clip_triangles(tris: &[Vec2], r: &Bounds2) -> Vec<Vec2> {
clip_triangles_within(tris, r, usize::MAX).0
}
/// [`clip_triangles`] up to `max` points; false with the triangles that fit when it stopped there.
pub fn clip_triangles_within(tris: &[Vec2], r: &Bounds2, max: usize) -> (Vec<Vec2>, bool) {
let mut out = Vec::new(); let mut out = Vec::new();
for t in tris.as_chunks::<3>().0 { for t in tris.as_chunks::<3>().0 {
let fits = if t.iter().all(|p| r.contains(*p)) { push_triangle(&mut out, *t, max) } else { push_fan(&mut out, &clip_polygon(t, r), max) }; if t.iter().all(|p| r.contains(*p)) {
if !fits { out.extend_from_slice(t);
return (out, false); continue;
}
let poly = clip_polygon(t, r);
if let Some(first) = poly.first().copied() {
for w in poly.get(1..).unwrap_or(&[]).windows(2) {
if let (Some(b), Some(c)) = (w.first(), w.get(1)) {
out.extend_from_slice(&[first, *b, *c]);
}
}
} }
} }
(out, true) out
}
/// Append triangle `t` to `out` when that keeps it within `max` points.
fn push_triangle(out: &mut Vec<Vec2>, t: [Vec2; 3], max: usize) -> bool {
if out.len().saturating_add(3) > max {
return false;
}
out.extend_from_slice(&t);
true
}
/// Append the convex polygon `poly` to `out` as a fan of triangles, while they fit within `max`
/// points; false at the first that doesn't.
fn push_fan(out: &mut Vec<Vec2>, poly: &[Vec2], max: usize) -> bool {
let Some(first) = poly.first().copied() else { return true };
poly.get(1..).unwrap_or(&[]).windows(2).all(|w| match (w.first(), w.get(1)) {
(Some(b), Some(c)) => push_triangle(out, [first, *b, *c], max),
_ => true,
})
} }
/// Most vertices a clip boundary keeps (denser outlines are thinned; hostile files). /// Most vertices a clip boundary keeps (denser outlines are thinned; hostile files).
@@ -425,34 +355,34 @@ impl PolyClip {
} }
/// Clip a polyline; returns the visible pieces (each with at least two points). /// Clip a polyline; returns the visible pieces (each with at least two points).
pub fn clip_polyline(&self, pts: &[Vec2]) -> Vec<Vec<Vec2>> { pub fn clip_polyline(&self, pts: &[Vec2]) -> Vec<Vec<Vec2>> {
self.clip_polyline_within(pts, Cap::NONE).0 let mut out: Vec<Vec<Vec2>> = Vec::new();
} let mut cur: Vec<Vec2> = Vec::new();
/// [`PolyClip::clip_polyline`] within `cap`; false with the pieces when the cap stopped them.
/// A segment can cross the outline at each of its edges, so the pieces can have far more
/// points than the polyline.
pub fn clip_polyline_within(&self, pts: &[Vec2], cap: Cap) -> (Vec<Vec<Vec2>>, bool) {
self.cut_polyline(pts, cap, PolyClip::clip_segment)
}
/// The pieces of polyline `pts` that `segment` keeps of each of its segments, joined where
/// they meet, within `cap`.
fn cut_polyline(&self, pts: &[Vec2], cap: Cap, segment: fn(&PolyClip, Vec2, Vec2, &mut Vec<(Vec2, Vec2)>)) -> (Vec<Vec<Vec2>>, bool) {
let mut out = Pieces::new(cap);
let mut pieces = Vec::new(); let mut pieces = Vec::new();
for w in pts.windows(2) { for w in pts.windows(2) {
if out.cut {
break;
}
let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue };
pieces.clear(); pieces.clear();
segment(self, *a, *b, &mut pieces); self.clip_segment(*a, *b, &mut pieces);
if pieces.is_empty() { if pieces.is_empty() {
out.end(); if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
} }
for (p, q) in pieces.drain(..) { for (p, q) in pieces.drain(..) {
out.segment(p, q); if !cur.last().is_some_and(|l| l.near(p, 1e-12)) {
if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
cur.push(p);
}
cur.push(q);
} }
} }
out.finish() if cur.len() >= 2 {
out.push(cur);
}
out
} }
/// Clip an infinite line (or a ray when `ray`) to the region. /// Clip an infinite line (or a ray when `ray`) to the region.
pub fn clip_infinite(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec<Vec<Vec2>> { pub fn clip_infinite(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec<Vec<Vec2>> {
@@ -463,11 +393,6 @@ impl PolyClip {
} }
/// Clip a triangle list (three vertices per triangle) to the region, re-triangulating as fans. /// Clip a triangle list (three vertices per triangle) to the region, re-triangulating as fans.
pub fn clip_triangles(&self, tris: &[Vec2]) -> Vec<Vec2> { pub fn clip_triangles(&self, tris: &[Vec2]) -> Vec<Vec2> {
self.clip_triangles_within(tris, usize::MAX).0
}
/// [`PolyClip::clip_triangles`] up to `max` points; false with the triangles that fit when it
/// stopped there (or past 6,000,000 points, for hostile files).
pub fn clip_triangles_within(&self, tris: &[Vec2], max: usize) -> (Vec<Vec2>, bool) {
let mut out = Vec::new(); let mut out = Vec::new();
for t in tris.as_chunks::<3>().0 { for t in tris.as_chunks::<3>().0 {
let tb = Bounds2::from_points(t.iter().copied()); let tb = Bounds2::from_points(t.iter().copied());
@@ -476,21 +401,27 @@ impl PolyClip {
} }
// Wholly inside: no outline edge crosses it. // Wholly inside: no outline edge crosses it.
if t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty()) { if t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty()) {
if !push_triangle(&mut out, *t, max) { out.extend_from_slice(t);
return (out, false);
}
continue; continue;
} }
for (c, cb) in &self.tris { for (c, cb) in &self.tris {
if !cb.intersects(&tb) { if !cb.intersects(&tb) {
continue; continue;
} }
if !push_fan(&mut out, &clip_convex(t, c), max) || out.len() > 6_000_000 { let poly = clip_convex(t, c);
return (out, false); if let Some(first) = poly.first().copied() {
for w in poly.get(1..).unwrap_or(&[]).windows(2) {
if let (Some(b), Some(c)) = (w.first(), w.get(1)) {
out.extend_from_slice(&[first, *b, *c]);
}
}
}
if out.len() > 6_000_000 {
return out;
} }
} }
} }
(out, true) out
} }
/// Clip a segment the other way round (an inverted XCLIP): the pieces outside the region. /// Clip a segment the other way round (an inverted XCLIP): the pieces outside the region.
@@ -513,12 +444,34 @@ impl PolyClip {
} }
/// Clip a polyline to outside the region (an inverted XCLIP); the visible pieces. /// Clip a polyline to outside the region (an inverted XCLIP); the visible pieces.
pub fn clip_polyline_outside(&self, pts: &[Vec2]) -> Vec<Vec<Vec2>> { pub fn clip_polyline_outside(&self, pts: &[Vec2]) -> Vec<Vec<Vec2>> {
self.clip_polyline_outside_within(pts, Cap::NONE).0 let mut out: Vec<Vec<Vec2>> = Vec::new();
} let mut cur: Vec<Vec2> = Vec::new();
/// [`PolyClip::clip_polyline_outside`] within `cap`; false with the pieces when the cap let mut pieces = Vec::new();
/// stopped them. for w in pts.windows(2) {
pub fn clip_polyline_outside_within(&self, pts: &[Vec2], cap: Cap) -> (Vec<Vec<Vec2>>, bool) { let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue };
self.cut_polyline(pts, cap, PolyClip::clip_segment_outside) pieces.clear();
self.clip_segment_outside(*a, *b, &mut pieces);
if pieces.is_empty() {
if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
}
for (p, q) in pieces.drain(..) {
if !cur.last().is_some_and(|l| l.near(p, 1e-12)) {
if cur.len() >= 2 {
out.push(std::mem::take(&mut cur));
}
cur.clear();
cur.push(p);
}
cur.push(q);
}
}
if cur.len() >= 2 {
out.push(cur);
}
out
} }
/// Clip an infinite line (or a ray) to outside the region: the line cut where it crosses. /// Clip an infinite line (or a ray) to outside the region: the line cut where it crosses.
pub fn clip_infinite_outside(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec<Vec<Vec2>> { pub fn clip_infinite_outside(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec<Vec<Vec2>> {
@@ -535,19 +488,14 @@ impl PolyClip {
/// Fill triangles outside the region (an inverted XCLIP). A triangle wholly inside goes; one /// Fill triangles outside the region (an inverted XCLIP). A triangle wholly inside goes; one
/// the outline crosses stays whole (fills are not cut against the outside). /// the outline crosses stays whole (fills are not cut against the outside).
pub fn clip_triangles_outside(&self, tris: &[Vec2]) -> Vec<Vec2> { pub fn clip_triangles_outside(&self, tris: &[Vec2]) -> Vec<Vec2> {
self.clip_triangles_outside_within(tris, usize::MAX).0
}
/// [`PolyClip::clip_triangles_outside`] up to `max` points; false with the triangles that fit
/// when it stopped there.
pub fn clip_triangles_outside_within(&self, tris: &[Vec2], max: usize) -> (Vec<Vec2>, bool) {
let mut out = Vec::new(); let mut out = Vec::new();
for t in tris.as_chunks::<3>().0 { for t in tris.as_chunks::<3>().0 {
let inside = t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty()); let inside = t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty());
if !inside && !push_triangle(&mut out, *t, max) { if !inside {
return (out, false); out.extend_from_slice(t);
} }
} }
(out, true) out
} }
} }
@@ -655,89 +603,6 @@ mod tests {
assert!(c.clip_polyline(&[Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]).is_empty()); assert!(c.clip_polyline(&[Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]).is_empty());
} }
#[test]
fn clips_stop_at_their_cap_and_say_so() {
// A zigzag across the rectangle's top edge: a piece for each dip below it.
let zig: Vec<Vec2> = (0..41).map(|i| Vec2::new(0.25 * f64::from(i), if i % 2 == 0 { 9.0 } else { 11.0 })).collect();
let all = clip_polyline(&zig, &r());
let n: usize = all.iter().map(Vec::len).sum();
assert!(all.len() > 10 && n > all.len() * 2, "{} pieces, {n} points", all.len());
assert_eq!(clip_polyline_within(&zig, &r(), Cap { points: n, pieces: all.len() }), (all.clone(), true));
// Cut by points: a prefix of the pieces, the last of which may end early.
let (cut, whole) = clip_polyline_within(&zig, &r(), Cap { points: n - 2, pieces: usize::MAX });
assert!(!whole && cut.iter().map(Vec::len).sum::<usize>() <= n - 2);
let last = cut.len() - 1;
assert!(cut[..last] == all[..last] && all[last].starts_with(&cut[last]), "{cut:?}");
// Cut by pieces.
assert_eq!(clip_polyline_within(&zig, &r(), Cap { points: usize::MAX, pieces: 3 }), (all[..3].to_vec(), false));
// Wholly inside but past the cap: not copied whole.
let inside = [Vec2::new(1.0, 1.0), Vec2::new(2.0, 1.0), Vec2::new(3.0, 1.0), Vec2::new(4.0, 1.0)];
assert_eq!(clip_polyline_within(&inside, &r(), Cap { points: 3, pieces: 1 }), (vec![inside[..3].to_vec()], false));
// A comb of 1,000 teeth: a line across it is cut into 1,000 pieces, so the pieces of a
// polyline can have about 1,000 times its points.
let teeth = 1000;
let mut comb = vec![Vec2::new(0.0, 0.0), Vec2::new(2.0 * f64::from(teeth) - 1.0, 0.0)];
for k in (0..teeth).rev() {
let x = 2.0 * f64::from(k);
comb.extend([Vec2::new(x + 1.0, 10.0), Vec2::new(x, 10.0)]);
if k > 0 {
comb.extend([Vec2::new(x, 1.0), Vec2::new(x - 1.0, 1.0)]);
}
}
let c = PolyClip::new(&comb).unwrap();
let line = [Vec2::new(-1.0, 5.0), Vec2::new(2.0 * f64::from(teeth), 5.0)];
assert_eq!(c.clip_polyline(&line).len(), 1000);
let (cut, whole) = c.clip_polyline_within(&line, Cap { points: 101, pieces: usize::MAX });
assert!(!whole && cut.len() == 50 && cut.iter().all(|p| p.len() == 2), "{}", cut.len());
assert_eq!(c.clip_polyline_within(&line, Cap { points: usize::MAX, pieces: 10 }).0.len(), 10);
// Outside it: the gaps between the teeth and both ends.
assert_eq!(c.clip_polyline_outside(&line).len(), 1001);
let (cut, whole) = c.clip_polyline_outside_within(&line, Cap { points: usize::MAX, pieces: 10 });
assert!(!whole && cut.len() == 10);
// Triangles over the rectangle's corner: each becomes a fan of three.
let corner = [Vec2::new(-0.5, -0.5), Vec2::new(1.5, 0.5), Vec2::new(0.5, 1.5)];
let tris: Vec<Vec2> = corner.iter().copied().cycle().take(300).collect();
let all = clip_triangles(&tris, &r());
assert_eq!(all.len(), 900);
assert_eq!(clip_triangles_within(&tris, &r(), 900), (all.clone(), true));
assert_eq!(clip_triangles_within(&tris, &r(), 100), (all[..99].to_vec(), false));
let c = notched();
let all = c.clip_triangles(&tris);
let (cut, whole) = c.clip_triangles_within(&tris, 30);
assert!(!whole && cut.len() == 30 && all.len() > 30 && all.starts_with(&cut), "{} of {}", cut.len(), all.len());
assert_eq!(c.clip_triangles_within(&tris, all.len()), (all, true));
// Triangles wholly inside are kept whole, up to the cap too.
let inside: Vec<Vec2> = [Vec2::new(1.0, 1.0), Vec2::new(2.0, 1.0), Vec2::new(1.0, 2.0)].iter().copied().cycle().take(30).collect();
assert_eq!(c.clip_triangles_within(&inside, 10), (inside[..9].to_vec(), false));
assert_eq!(c.clip_triangles_within(&inside, 30), (inside.clone(), true));
// Outside the notched square, triangles away from it are kept whole.
let away: Vec<Vec2> = [Vec2::new(20.0, 20.0), Vec2::new(21.0, 20.0), Vec2::new(20.0, 21.0)].iter().copied().cycle().take(30).collect();
assert_eq!(c.clip_triangles_outside_within(&away, 10), (away[..9].to_vec(), false));
assert_eq!(c.clip_triangles_outside_within(&away, 30), (away.clone(), true));
}
#[test]
fn a_piece_the_cap_has_no_room_for_is_not_built() {
// One piece fits the cap; the next one stops the pieces before any of its points are
// copied.
let mut pieces = Pieces::new(Cap { points: 1_000, pieces: 1 });
pieces.segment(Vec2::new(1.0, 1.0), Vec2::new(10.0, 1.0));
pieces.end();
pieces.segment(Vec2::new(10.0, 2.0), Vec2::new(1.0, 2.0));
assert!(pieces.cut && pieces.cur.is_empty() && pieces.points == 2, "{} points", pieces.points);
// Through the rectangle: out past its right edge, back in, and on inside for 1,000 points.
let back: Vec<Vec2> = [Vec2::new(1.0, 1.0), Vec2::new(11.0, 1.0), Vec2::new(11.0, 2.0), Vec2::new(1.0, 2.0)]
.into_iter()
.chain((0..1000).map(|i| Vec2::new(1.0 + f64::from(i % 2), 3.0 + f64::from(i) * 0.005)))
.collect();
let first = vec![Vec2::new(1.0, 1.0), Vec2::new(10.0, 1.0)];
assert_eq!(clip_polyline_within(&back, &r(), Cap { points: usize::MAX, pieces: 1 }), (vec![first.clone()], false));
// A piece that fits exactly, with nothing visible after it, is whole.
assert_eq!(clip_polyline_within(&back[..3], &r(), Cap { points: 2, pieces: 1 }), (vec![first], true));
}
#[test] #[test]
fn triangles() { fn triangles() {
let t = clip_triangles(&[Vec2::new(-5.0, 0.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 10.0)], &r()); let t = clip_triangles(&[Vec2::new(-5.0, 0.0), Vec2::new(5.0, 0.0), Vec2::new(5.0, 10.0)], &r());
-52
View File
@@ -652,58 +652,6 @@ fn radial_and_angular_text() {
assert_eq!(g.value, "1.57r"); assert_eq!(g.value, "1.57r");
} }
#[test]
fn radial_dimpost_replaces_only_automatic_radius_and_diameter_prefixes() {
let linear = lin((0.0, 0.0), (5.0, 0.0), (0.0, 4.0), 0.0);
let radius = Dimension { kind: DimKind::Radius, defpt: Vec3::ZERO, p15: Vec3::new(5.0, 0.0, 0.0), ..linear.clone() };
let diameter = Dimension { kind: DimKind::Diameter, defpt: Vec3::new(-5.0, 0.0, 0.0), ..radius.clone() };
let arc = Dimension {
kind: DimKind::ArcLength,
defpt: Vec3::new(4.0, 4.0, 0.0),
p13: Vec3::new(5.0, 0.0, 0.0),
p14: Vec3::new(0.0, 5.0, 0.0),
..linear.clone()
};
let arc_style = DimStyle { arc_symbol: 0, post: "ARC <>".into(), ..DimStyle::default() };
assert!(dimension_geometry(&arc, &arc_style, 1.0).value.starts_with("ARC ⌒"));
for (post, expected) in [
("", ["R5", "%%c10", "5"]),
("<> REF", ["R5 REF", "%%c10 REF", "5 REF"]),
(" REF", ["R5 REF", "%%c10 REF", "5 REF"]),
("PAIR <>", ["PAIR 5", "PAIR 10", "PAIR 5"]),
("PAIR R<>", ["PAIR R5", "PAIR R10", "PAIR R5"]),
("%%c<>", ["%%c5", "%%c10", "%%c5"]),
] {
let st = DimStyle { decimals: 0, post: post.into(), ..DimStyle::default() };
for (d, want) in [&radius, &diameter, &linear].into_iter().zip(expected) {
assert_eq!(dimension_geometry(d, &st, 1.0).mtext_contents(), want, "{:?}, DIMPOST {post:?}", d.kind);
}
}
}
#[test]
fn radial_dimpost_keeps_jogged_radius_tolerances_and_alternate_units() {
let mut d = lin((0.0, 0.0), (0.0, 0.0), (0.0, 0.0), 0.0);
d.kind = DimKind::Radius;
d.p15 = Vec3::new(5.0, 0.0, 0.0);
d.marks.jogged = Some(cadcraft_doc::JoggedRadius { center: Vec3::new(0.0, -4.0, 0.0), jog: Vec3::new(2.5, -2.0, 0.0) });
let st = DimStyle {
post: "PAIR <> REF".into(),
decimals: 1,
tolerance: true,
tol_plus: 0.1,
tol_minus: 0.1,
tol_decimals: 1,
alt: true,
alt_factor: 2.0,
alt_decimals: 1,
alt_post: "ALT <>".into(),
..DimStyle::default()
};
assert_eq!(dimension_geometry(&d, &st, 1.0).value, "PAIR 5.0 REF±0.1 REF [ALT 10.0]");
}
#[test] #[test]
fn hostile_styles_do_not_panic() { fn hostile_styles_do_not_panic() {
let d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); let d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0);
+1 -6
View File
@@ -1,4 +1,4 @@
use super::{DimKind, DimStyle, Dimension, NumFormat, TextFont, format_decimal, format_linear}; use super::{DimStyle, Dimension, NumFormat, TextFont, format_decimal, format_linear};
/// Format a linear measurement per the style (plain text). /// Format a linear measurement per the style (plain text).
pub fn format_linear_value(v: f64, st: &DimStyle) -> String { pub fn format_linear_value(v: f64, st: &DimStyle) -> String {
@@ -17,11 +17,6 @@ pub(super) fn linear_text(meas: f64, d: &Dimension, st: &DimStyle, prefix: &str)
let lo = format_linear(v - st.tol_minus, &nf).1; let lo = format_linear(v - st.tol_minus, &nf).1;
format!("{{\\H{};\\S{up}^{lo};}}", tol_height_code(st)) format!("{{\\H{};\\S{up}^{lo};}}", tol_height_code(st))
} else { } else {
// An authored DIMPOST prefix replaces the default radius or diameter symbol.
let prefix = match d.kind {
DimKind::Radius | DimKind::Diameter if st.post.find("<>").is_some_and(|marker| marker > 0) => "",
_ => prefix,
};
format!("{prefix}{}", format_linear(v, &nf).1) format!("{prefix}{}", format_linear(v, &nf).1)
}; };
let mut s = post(&st.post, &main); let mut s = post(&st.post, &main);
+3 -5
View File
@@ -107,11 +107,9 @@ pub struct DisplayList {
pub sheet: Option<Sheet>, pub sheet: Option<Sheet>,
/// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]). /// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]).
pub expanded: usize, pub expanded: usize,
/// The block-expansion budget, the point budget ([`crate::MAX_DISPLAY_POINTS`]) or the /// The block-expansion budget or the point budget ([`crate::MAX_DISPLAY_POINTS`]) was spent:
/// primitive budget ([`crate::MAX_DISPLAY_PRIMS`]) was spent: block contents or objects past it /// block contents or objects past it are not in the list; or a dashed run was drawn
/// are not in the list; or a dashed run was drawn continuous past a dash limit /// continuous past a dash limit ([`DisplayList::undashed`]). The screen,
/// ([`DisplayList::undashed`]); or plot style ends, joins or fill patterns were left out past
/// the point budget ([`pen::apply`]). The screen,
/// plots and exports draw what is here; the control channel and the MCP render report this, /// plots and exports draw what is here; the control channel and the MCP render report this,
/// so an output that leaves contents out is never silent (#1070). /// so an output that leaves contents out is never silent (#1070).
pub truncated: bool, pub truncated: bool,
+2 -13
View File
@@ -22,9 +22,8 @@ pub(crate) fn entity(b: &mut Builder, ctx: &Ctx, e: &Entity) {
if ctx.d.is_hidden_object(e.handle) || b.opts.cancelled() { if ctx.d.is_hidden_object(e.handle) || b.opts.cancelled() {
return; return;
} }
// Once the build holds all the points or primitives it may, nothing more is drawn (or // Once the build holds all the points it may, nothing more is drawn (or computed).
// computed). if b.points_spent() {
if b.spent() {
b.list.truncated = true; b.list.truncated = true;
return; return;
} }
@@ -60,15 +59,6 @@ fn shown_transparency(b: &mut Builder, ctx: &Ctx, e: &Entity, layer_transparency
own 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) { 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 // 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). // model space seen through it, else the drawing's (CANNOSCALE in model space, 1:1 on paper).
@@ -92,7 +82,6 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
if !visible { if !visible {
return; return;
} }
let fade = fade.max(refedit_fade(b, ctx, e));
let own = shown_transparency(b, ctx, e, layer_transparency, fade); let own = shown_transparency(b, ctx, e, layer_transparency, fade);
// A plot style's linetype replaces the object's. // A plot style's linetype replaces the object's.
let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) {
+8 -3
View File
@@ -10,7 +10,7 @@
use super::{Builder, Ctx, Ink, fill, ink, max_scale}; use super::{Builder, Ctx, Ink, fill, ink, max_scale};
use cadcraft_color::{Color, Rgb}; use cadcraft_color::{Color, Rgb};
use cadcraft_doc::library::{PatternLine, effective_hatch_pattern_scale, pattern_for}; use cadcraft_doc::library::{PatternLine, pattern_for};
use cadcraft_doc::{Drawing, Entity, Gradient, Hatch}; use cadcraft_doc::{Drawing, Entity, Gradient, Hatch};
use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
@@ -439,6 +439,11 @@ fn lines_of(d: &Drawing, h: &Hatch) -> Vec<PatternLine> {
} }
} }
/// The hatch's pattern scale (1 when unusable).
fn scale_of(h: &Hatch) -> f64 {
if h.scale.is_finite() && h.scale > 1e-9 { h.scale } else { 1.0 }
}
/// True when, at `px` hatch units per pixel, the pattern covers its area on screen, so drawing /// True when, at `px` hatch units per pixel, the pattern covers its area on screen, so drawing
/// it line by line would fill (nearly) every pixel anyway. Each line, dash or dot is drawn at /// it line by line would fill (nearly) every pixel anyway. Each line, dash or dot is drawn at
/// least a pixel wide, so that is the case when /// least a pixel wide, so that is the case when
@@ -452,7 +457,7 @@ pub fn reads_solid(d: &Drawing, h: &Hatch, px: f64) -> bool {
if !(px.is_finite() && px > 0.0) { if !(px.is_finite() && px > 0.0) {
return false; return false;
} }
let scale = effective_hatch_pattern_scale(h.scale); let scale = scale_of(h);
let mut coverage = 0.0; let mut coverage = 0.0;
for f in lines_of(d, h) { for f in lines_of(d, h) {
let spacing = (f.delta.1 * scale).abs(); let spacing = (f.delta.1 * scale).abs();
@@ -514,7 +519,7 @@ fn pattern_lines_within(
work_limit: u64, work_limit: u64,
) -> Vec<Vec<Vec2>> { ) -> Vec<Vec<Vec2>> {
let lines = lines_of(d, h); let lines = lines_of(d, h);
let scale = effective_hatch_pattern_scale(h.scale); let scale = scale_of(h);
let px = if px.is_finite() && px > 0.0 { px } else { 0.0 }; let px = if px.is_finite() && px > 0.0 { px } else { 0.0 };
let mut out = Vec::new(); let mut out = Vec::new();
// Shared work budget across all families and spans, counting dash-processing steps even when // Shared work budget across all families and spans, counting dash-processing steps even when
+13 -109
View File
@@ -92,11 +92,6 @@ struct Ctx<'a> {
top: Handle, top: Handle,
/// Layers frozen in the viewport being drawn. /// Layers frozen in the viewport being drawn.
frozen: &'a [String], frozen: &'a [String],
/// Built as loose entities ([`build_entities_in_viewport`]: for a selection, a highlight or a
/// preview) and not to draw a viewport: a point on the layer Defpoints that is a part of a
/// block is then kept whatever layers are given as frozen
/// ([`cadcraft_doc::point_on_defpoints`]).
selecting: bool,
/// Per-viewport layer colour overrides of the viewport being drawn. /// Per-viewport layer colour overrides of the viewport being drawn.
vp_colors: &'a [(String, Color)], vp_colors: &'a [(String, Color)],
/// Extra linetype scale for model space seen through a viewport: 1 / viewport scale when /// Extra linetype scale for model space seen through a viewport: 1 / viewport scale when
@@ -139,10 +134,6 @@ struct Builder<'a> {
points: &'a std::sync::atomic::AtomicUsize, points: &'a std::sync::atomic::AtomicUsize,
/// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests). /// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests).
max_points: usize, max_points: usize,
/// Primitives the whole build has charged so far, shared like `points`.
prims: &'a std::sync::atomic::AtomicUsize,
/// The most primitives the build may hold: [`MAX_DISPLAY_PRIMS`] (less in tests).
max_prims: usize,
/// Dash pattern elements the whole build has laid out so far, shared like `points`. /// Dash pattern elements the whole build has laid out so far, shared like `points`.
dashes: &'a std::sync::atomic::AtomicUsize, dashes: &'a std::sync::atomic::AtomicUsize,
/// The most dash pattern elements the build may lay out: [`MAX_DASH_ELEMENTS`] (less in tests). /// The most dash pattern elements the build may lay out: [`MAX_DASH_ELEMENTS`] (less in tests).
@@ -150,24 +141,6 @@ struct Builder<'a> {
/// The loops of the drawing's block graph, worked out once for the whole build when a search /// The loops of the drawing's block graph, worked out once for the whole build when a search
/// near a dimension's block does not settle whether it leads back (see [`loops`]). /// near a dimension's block does not settle whether it leads back (see [`loops`]).
loops: &'a std::sync::OnceLock<loops::BlockLoops>, loops: &'a std::sync::OnceLock<loops::BlockLoops>,
/// 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 /// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy
@@ -186,27 +159,6 @@ pub const MAX_BLOCK_EXPANSION: usize = 2_000_000;
/// for a plot) is expected to hold a few tens of millions. /// for a plot) is expected to hold a few tens of millions.
pub const MAX_DISPLAY_POINTS: usize = 64_000_000; pub const MAX_DISPLAY_POINTS: usize = 64_000_000;
/// Upper bound on the primitives one display list holds. Each primitive is charged at least one
/// point, so on a 64-bit target [`MAX_DISPLAY_POINTS`] bounds them already and this is the same
/// number. A 32-bit target (the web build) has 2 GiB per allocation and 4 GiB in all: at 40 bytes
/// a primitive, a list of more than 2^25 one-point primitives (a dotted linetype) needed more than
/// 2 GiB when its primitive vector grew, and the build panicked with "capacity overflow" (#1603).
/// There a list holds at most 2^24 primitives (640 MiB of them), below that limit to leave room
/// for the canvas's vertex data and for the next list, built while this one is still shown. Past
/// the limit nothing more is drawn and [`DisplayList::truncated`] is set.
pub const MAX_DISPLAY_PRIMS: usize = if usize::BITS >= 64 { MAX_DISPLAY_POINTS } else { 1 << 24 };
// A vector holding the most primitives (or points) a list may hold can still double without
// passing `isize::MAX` bytes, the most one allocation can take; the wasm build checks this for
// 32-bit memory.
const _: () = assert!(MAX_DISPLAY_PRIMS <= isize::MAX as usize / 2 / std::mem::size_of::<DPrim>());
const _: () = assert!(MAX_DISPLAY_POINTS <= isize::MAX as usize / 2 / std::mem::size_of::<Vec2>());
const _: () = assert!(MAX_DISPLAY_PRIMS <= isize::MAX as usize / 2 / std::mem::size_of::<Pen>());
// Plotted text and images hold at most one entry per primitive and grow one push at a time, so by
// doubling from a power of two: the most they reach is the power of two at or above the limit.
const _: () = assert!(MAX_DISPLAY_PRIMS.next_power_of_two() <= isize::MAX as usize / std::mem::size_of::<PlotText>());
const _: () = assert!(MAX_DISPLAY_PRIMS.next_power_of_two() <= isize::MAX as usize / std::mem::size_of::<DImage>());
/// Upper bound on the dash pattern elements one dashed run (a line, an arc, a polyline segment or /// Upper bound on the dash pattern elements one dashed run (a line, an arc, a polyline segment or
/// a PLINEGEN polyline) is laid out over: a longer pattern repeated more often is drawn /// a PLINEGEN polyline) is laid out over: a longer pattern repeated more often is drawn
/// continuous, and [`DisplayList::undashed`] counts it. A plot keeps the dashes of a run of any /// continuous, and [`DisplayList::undashed`] counts it. A plot keeps the dashes of a run of any
@@ -454,12 +406,9 @@ impl<'a> Builder<'a> {
transparency: self.transparency, transparency: self.transparency,
points: self.points, points: self.points,
max_points: self.max_points, max_points: self.max_points,
prims: self.prims,
max_prims: self.max_prims,
dashes: self.dashes, dashes: self.dashes,
max_dashes: self.max_dashes, max_dashes: self.max_dashes,
loops: self.loops, loops: self.loops,
fade: self.fade,
} }
} }
/// Whether block `to` leads back to block `from` in `d`, the drawing being built (see /// Whether block `to` leads back to block `from` in `d`, the drawing being built (see
@@ -468,11 +417,10 @@ impl<'a> Builder<'a> {
loops::leads_back(d, self.loops, from, to) loops::leads_back(d, self.loops, from, to)
} }
/// Take one unit of the block-expansion budget; false once it is spent, or once the build /// Take one unit of the block-expansion budget; false once it is spent, or once the build
/// holds all the points ([`MAX_DISPLAY_POINTS`]) or primitives ([`MAX_DISPLAY_PRIMS`]) it may, /// holds all the points it may ([`MAX_DISPLAY_POINTS`]), so block copies stop being visited.
/// so block copies stop being visited.
fn expand(&mut self) -> bool { fn expand(&mut self) -> bool {
self.list.expanded = self.list.expanded.saturating_add(1); self.list.expanded = self.list.expanded.saturating_add(1);
let ok = !self.spent() let ok = !self.points_spent()
&& match self.shared_budget { && match self.shared_budget {
Some(spent) => spent.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < MAX_BLOCK_EXPANSION, Some(spent) => spent.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < MAX_BLOCK_EXPANSION,
None => self.list.expanded <= MAX_BLOCK_EXPANSION, None => self.list.expanded <= MAX_BLOCK_EXPANSION,
@@ -482,63 +430,22 @@ impl<'a> Builder<'a> {
} }
ok ok
} }
/// Whether the build holds all the points or all the primitives it may: nothing more is drawn. /// Whether the build holds all the points it may: nothing more is drawn.
fn spent(&self) -> bool { fn points_spent(&self) -> bool {
use std::sync::atomic::Ordering::Relaxed; self.points.load(std::sync::atomic::Ordering::Relaxed) >= self.max_points
self.points.load(Relaxed) >= self.max_points || (self.counts_prims() && self.prims.load(Relaxed) >= self.max_prims)
} }
/// Whether the primitive budget can bind. Every primitive is charged at least one point, so a /// Charge `n` points to the build's [`MAX_DISPLAY_POINTS`] budget before they are pushed;
/// primitive limit at or above the point limit (64-bit targets) never does and isn't counted. /// false (and the list marked truncated) when they don't fit, and nothing is pushed. Once the
fn counts_prims(&self) -> bool { /// budget is spent nothing more is added to the count, so it stays within the limit plus one
self.max_prims < self.max_points /// primitive per thread building in parallel.
}
/// Spend the build: nothing more is drawn, as when a budget runs out. For a list without room
/// for what is appended to it (see [`Limits`]), so the objects left are not worked out only to
/// be refused.
fn spend(&mut self) {
self.points.fetch_max(self.max_points, std::sync::atomic::Ordering::Relaxed);
self.list.truncated = true;
}
/// Charge one primitive of `n` points to the build's budgets ([`MAX_DISPLAY_POINTS`] and
/// [`MAX_DISPLAY_PRIMS`]) before it is pushed; false (and the list marked truncated) when it
/// doesn't fit, and nothing is pushed. Once a budget is spent nothing more is added to the
/// counts, so they stay within their limits plus one primitive per thread building in parallel.
/// The list itself must have room too: clipped copies appended to it are not in the counts. A
/// list without room spends the build.
fn charge(&mut self, n: usize) -> bool { fn charge(&mut self, n: usize) -> bool {
use std::sync::atomic::Ordering::Relaxed; use std::sync::atomic::Ordering::Relaxed;
if !self.spent() && !self.limits().room(&mut self.list, n) { let ok = !self.points_spent() && self.points.fetch_add(n, Relaxed).saturating_add(n) <= self.max_points;
self.spend();
}
let ok = !self.spent()
&& self.points.fetch_add(n, Relaxed).saturating_add(n) <= self.max_points
&& (!self.counts_prims() || self.prims.fetch_add(1, Relaxed) < self.max_prims);
if !ok { if !ok {
self.list.truncated = true; self.list.truncated = true;
} }
ok ok
} }
/// What one list of this build may hold, for the clipped copies appended to it.
fn limits(&self) -> Limits {
Limits { points: self.max_points, prims: self.max_prims }
}
/// Join the parts of a list built on all cores to this builder's list, in drawing order and
/// within its limits ([`Limits`]): the clipped copies a part holds are in no count, so the
/// parts can hold more together than one list may. At the first part that doesn't fit the build
/// is spent and the parts left are not joined.
#[cfg(not(target_arch = "wasm32"))]
fn join(&mut self, parts: Vec<DisplayList>) {
let points = |l: &DisplayList| l.verts.len().saturating_add(l.tris.len());
for part in parts {
if self.list.prims.len().saturating_add(part.prims.len()) > self.max_prims
|| points(&self.list).saturating_add(points(&part)) > self.max_points
{
self.spend();
return;
}
display::append(&mut self.list, part);
}
}
} }
/// The build's dash budget ([`MAX_DASH_ELEMENTS`]), charged as [`Builder::charge`] charges /// The build's dash budget ([`MAX_DASH_ELEMENTS`]), charged as [`Builder::charge`] charges
@@ -574,10 +481,7 @@ fn image_clip(i: &cadcraft_doc::Image, place: impl Fn(Vec2) -> Vec2) -> Option<V
} }
mod table; mod table;
pub use table::{ pub use table::{MAX_LAYOUT_CELLS, TableFill, TableGeom, TableLine, TableText, table_covered, table_geometry, table_style_of};
MAX_LAYOUT_CELLS, TableFill, TableGeom, TableLine, TableText, layout_table_text, table_covered, table_geometry, table_style_of,
table_text_mtext_params,
};
mod blocks; mod blocks;
mod dim_draw; mod dim_draw;
@@ -590,11 +494,11 @@ mod viewports;
pub use dim_draw::{dim_text, dimension_in}; pub use dim_draw::{dim_text, dimension_in};
pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha};
pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot}; pub use pipeline::{Options, build, build_entities, build_plot};
use props::{default_lineweight, resolve_common}; use props::{default_lineweight, resolve_common};
use text_entity::text_style; use text_entity::text_style;
pub use text_entity::{fitted_text_entity, layout_mtext_entity, place_text_entity, style_font, text_align}; pub use text_entity::{fitted_text_entity, layout_mtext_entity, place_text_entity, style_font, text_align};
use viewports::{Clip, Limits, append_clipped_keep}; use viewports::{Clip, append_clipped_keep};
pub use viewports::{clip_list, viewport_clip, viewport_content}; pub use viewports::{clip_list, viewport_clip, viewport_content};
#[cfg(test)] #[cfg(test)]
+15 -162
View File
@@ -13,14 +13,11 @@
//! The patterns are CADCraft's own definitions, measured in millimetres on paper and anchored to //! The patterns are CADCraft's own definitions, measured in millimetres on paper and anchored to
//! the paper origin. Layouts apply them while building (paper units are known); a model-space //! the paper origin. Layouts apply them while building (paper units are known); a model-space
//! plot applies them once its plot scale is known. //! plot applies them once its plot scale is known.
//!
//! This geometry is made after the build, outside its budgets, so the list stops at the build's
//! point limit, [`MAX_DISPLAY_POINTS`] (see [`apply`]).
use cadcraft_doc::{EndStyle, FillStyle, JoinStyle}; use cadcraft_doc::{EndStyle, FillStyle, JoinStyle};
use cadcraft_geom::Vec2; use cadcraft_geom::Vec2;
use crate::{DisplayList, Kind, MAX_DISPLAY_POINTS}; use crate::{DisplayList, Kind};
/// End, join and fill style a primitive prints with (all "use object" when no plot style table /// End, join and fill style a primitive prints with (all "use object" when no plot style table
/// is applied). /// is applied).
@@ -71,19 +68,7 @@ const ROUND_STEPS: usize = 12;
/// millimetres on paper. Lines with end or join styles become filled outlines and patterned /// millimetres on paper. Lines with end or join styles become filled outlines and patterned
/// fills become the pattern's pieces. Each primitive stays one primitive (same order, handle and /// fills become the pattern's pieces. Each primitive stays one primitive (same order, handle and
/// colour) and the pens are used up, so applying twice changes nothing. /// colour) and the pens are used up, so applying twice changes nothing.
///
/// The build's budgets don't count this geometry, and a 2-point line with round ends becomes 78
/// triangle corners, so the list holds at most [`MAX_DISPLAY_POINTS`] points: from the first
/// primitive whose geometry doesn't fit, the primitives left keep their plain line or solid fill
/// and the list is marked truncated. Without the limit a wide-line plot style on a list near the
/// budget made more points than the web build can allocate (#1603).
pub fn apply(list: &mut DisplayList, mm_per_unit: f64) { pub fn apply(list: &mut DisplayList, mm_per_unit: f64) {
apply_within(list, mm_per_unit, MAX_DISPLAY_POINTS);
}
/// [`apply`] with the list holding at most `max_points` points (polyline vertices and triangle
/// corners): the build's own limit, less in tests.
pub(crate) fn apply_within(list: &mut DisplayList, mm_per_unit: f64, max_points: usize) {
let pens = std::mem::take(&mut list.pens); let pens = std::mem::take(&mut list.pens);
if !(mm_per_unit.is_finite() && mm_per_unit > 0.0) { if !(mm_per_unit.is_finite() && mm_per_unit > 0.0) {
return; return;
@@ -91,23 +76,15 @@ pub(crate) fn apply_within(list: &mut DisplayList, mm_per_unit: f64, max_points:
let mut budget = MAX_PATTERN_CELLS; let mut budget = MAX_PATTERN_CELLS;
for (i, pen) in pens.iter().enumerate() { for (i, pen) in pens.iter().enumerate() {
let Some(p) = list.prims.get(i).copied() else { break }; let Some(p) = list.prims.get(i).copied() else { break };
let room = max_points.saturating_sub(list.verts.len().saturating_add(list.tris.len()));
let out = match p.kind { let out = match p.kind {
Kind::Polyline if pen.shapes_lines() && p.lw > WIDE_MM => { Kind::Polyline if pen.shapes_lines() && p.lw > WIDE_MM => {
let hw = f64::from(p.lw) / 2.0 / mm_per_unit; let hw = f64::from(p.lw) / 2.0 / mm_per_unit;
stroke_within(list.points(&p), hw, pen.end, pen.join, room) Some(stroke(list.points(&p), hw, pen.end, pen.join))
} }
Kind::Tris if pen.patterned() => { Kind::Tris if pen.patterned() => pattern(list.points(&p), pen.fill, PATTERN_MM / mm_per_unit, &mut budget),
let Some(out) = pattern_within(list.points(&p), pen.fill, PATTERN_MM / mm_per_unit, &mut budget, room) else { continue }; _ => None,
out
}
_ => continue,
}; };
if out.full { let Some(tris) = out else { continue };
list.truncated = true;
break;
}
let tris = out.pts;
let (Ok(start), Ok(len)) = (u32::try_from(list.tris.len()), u32::try_from(tris.len())) else { continue }; let (Ok(start), Ok(len)) = (u32::try_from(list.tris.len()), u32::try_from(tris.len())) else { continue };
if start.checked_add(len).is_none() { if start.checked_add(len).is_none() {
continue; continue;
@@ -121,38 +98,22 @@ pub(crate) fn apply_within(list: &mut DisplayList, mm_per_unit: f64, max_points:
} }
} }
/// Triangle corners being made, at most `max` of them: a triangle past it is left out and `full`
/// set, and the caller keeps the primitive as it was.
struct Out {
pts: Vec<Vec2>,
max: usize,
full: bool,
}
impl Out {
fn within(max: usize) -> Out {
Out { pts: Vec::new(), max, full: false }
}
}
/// Push triangle `a b c` counter-clockwise (so overlapping pieces fill as a union under the /// Push triangle `a b c` counter-clockwise (so overlapping pieces fill as a union under the
/// non-zero rule); degenerate ones are dropped. /// non-zero rule); degenerate ones are dropped.
fn tri(out: &mut Out, a: Vec2, b: Vec2, c: Vec2) { fn tri(out: &mut Vec<Vec2>, a: Vec2, b: Vec2, c: Vec2) {
let area = (b - a).cross(c - a); let area = (b - a).cross(c - a);
if !area.is_finite() || area.abs() <= 1e-300 { if !area.is_finite() || area.abs() <= 1e-300 {
return; return;
} }
if out.pts.len().saturating_add(3) > out.max { if area > 0.0 {
out.full = true; out.extend_from_slice(&[a, b, c]);
} else if area > 0.0 {
out.pts.extend_from_slice(&[a, b, c]);
} else { } else {
out.pts.extend_from_slice(&[a, c, b]); out.extend_from_slice(&[a, c, b]);
} }
} }
/// Fan of the arc around `c` from `from` to `to` (radius `r`), turning the short way. /// Fan of the arc around `c` from `from` to `to` (radius `r`), turning the short way.
fn round_fan(out: &mut Out, c: Vec2, r: f64, from: Vec2, to: Vec2) { fn round_fan(out: &mut Vec<Vec2>, c: Vec2, r: f64, from: Vec2, to: Vec2) {
let a0 = from.y.atan2(from.x); let a0 = from.y.atan2(from.x);
let mut sweep = to.y.atan2(to.x) - a0; let mut sweep = to.y.atan2(to.x) - a0;
while sweep > std::f64::consts::PI { while sweep > std::f64::consts::PI {
@@ -174,12 +135,7 @@ fn round_fan(out: &mut Out, c: Vec2, r: f64, from: Vec2, to: Vec2) {
/// corners ("use object" = round). A polyline whose last point is its first is closed: joins all /// corners ("use object" = round). A polyline whose last point is its first is closed: joins all
/// round, no ends. /// round, no ends.
pub fn stroke(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle) -> Vec<Vec2> { pub fn stroke(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle) -> Vec<Vec2> {
stroke_within(pts, hw, end, join, usize::MAX).pts let mut out = Vec::new();
}
/// [`stroke`], making at most `max` triangle corners (see [`Out`]).
fn stroke_within(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle, max: usize) -> Out {
let mut out = Out::within(max);
if !(hw.is_finite() && hw > 0.0) { if !(hw.is_finite() && hw > 0.0) {
return out; return out;
} }
@@ -224,7 +180,7 @@ fn stroke_within(pts: &[Vec2], hw: f64, end: EndStyle, join: JoinStyle, max: usi
} }
/// The cap at end point `p` of a line leaving it in unit direction `out_dir`. /// The cap at end point `p` of a line leaving it in unit direction `out_dir`.
fn cap(out: &mut Out, p: Vec2, out_dir: Vec2, hw: f64, end: EndStyle) { fn cap(out: &mut Vec<Vec2>, p: Vec2, out_dir: Vec2, hw: f64, end: EndStyle) {
let n = out_dir.perp() * hw; let n = out_dir.perp() * hw;
match end { match end {
EndStyle::Butt => {} EndStyle::Butt => {}
@@ -239,7 +195,7 @@ fn cap(out: &mut Out, p: Vec2, out_dir: Vec2, hw: f64, end: EndStyle) {
} }
/// The corner at `c` between a segment arriving in direction `d0` and one leaving in `d1`. /// The corner at `c` between a segment arriving in direction `d0` and one leaving in `d1`.
fn corner(out: &mut Out, c: Vec2, d0: Vec2, d1: Vec2, hw: f64, join: JoinStyle) { fn corner(out: &mut Vec<Vec2>, c: Vec2, d0: Vec2, d1: Vec2, hw: f64, join: JoinStyle) {
let turn = d0.cross(d1); let turn = d0.cross(d1);
if turn.abs() <= 1e-12 && d0.dot(d1) > 0.0 { if turn.abs() <= 1e-12 && d0.dot(d1) > 0.0 {
return; // straight on return; // straight on
@@ -328,17 +284,11 @@ fn band_range(t: &[Vec2; 3], axis: Vec2, pitch: f64) -> Option<(f64, f64)> {
/// The pieces of the triangles `tris` covered by `fill`'s pattern at repeat distance `pitch`, or /// The pieces of the triangles `tris` covered by `fill`'s pattern at repeat distance `pitch`, or
/// `None` (draw solid) when the pattern would take more than the remaining `budget` of cells. /// `None` (draw solid) when the pattern would take more than the remaining `budget` of cells.
pub fn pattern(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize) -> Option<Vec<Vec2>> { pub fn pattern(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize) -> Option<Vec<Vec2>> {
pattern_within(tris, fill, pitch, budget, usize::MAX).map(|out| out.pts)
}
/// [`pattern`], making at most `max` triangle corners (see [`Out`]). Once a triangle doesn't fit,
/// it stops with `full` set, before a later triangle can run out of cells and return `None`.
fn pattern_within(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize, max: usize) -> Option<Out> {
if !(pitch.is_finite() && pitch > 0.0) { if !(pitch.is_finite() && pitch > 0.0) {
return None; return None;
} }
let families = grids(fill, pitch); let families = grids(fill, pitch);
let mut out = Out::within(max); let mut out = Vec::new();
for t in tris.as_chunks::<3>().0 { for t in tris.as_chunks::<3>().0 {
if t.iter().any(|p| !p.is_finite()) { if t.iter().any(|p| !p.is_finite()) {
continue; continue;
@@ -346,11 +296,6 @@ fn pattern_within(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize
let [a, b, c] = *t; let [a, b, c] = *t;
let base: Vec<Vec2> = if (b - a).cross(c - a) >= 0.0 { vec![a, b, c] } else { vec![a, c, b] }; let base: Vec<Vec2> = if (b - a).cross(c - a) >= 0.0 { vec![a, b, c] } else { vec![a, c, b] };
for g in &families { for g in &families {
// Past the point limit: say so now. Running out of cells later would keep the fill
// solid without marking the list, and applying would go on.
if out.full {
return Some(out);
}
let (i0, i1) = band_range(t, g.a, g.pitch)?; let (i0, i1) = band_range(t, g.a, g.pitch)?;
let (j0, j1) = match g.b { let (j0, j1) = match g.b {
Some(axis) => band_range(t, axis, g.pitch)?, Some(axis) => band_range(t, axis, g.pitch)?,
@@ -388,7 +333,7 @@ fn pattern_within(tris: &[Vec2], fill: FillStyle, pitch: f64, budget: &mut usize
} }
/// Triangle fan of a convex polygon. /// Triangle fan of a convex polygon.
fn fan(out: &mut Out, poly: &[Vec2]) { fn fan(out: &mut Vec<Vec2>, poly: &[Vec2]) {
let Some(first) = poly.first().copied() else { return }; let Some(first) = poly.first().copied() else { return };
for w in poly.get(1..).unwrap_or(&[]).windows(2) { for w in poly.get(1..).unwrap_or(&[]).windows(2) {
if let [b, c] = w { if let [b, c] = w {
@@ -427,96 +372,4 @@ mod tests {
assert!(pattern(&big, FillStyle::Checkerboard, f64::NAN, &mut budget).is_none()); assert!(pattern(&big, FillStyle::Checkerboard, f64::NAN, &mut budget).is_none());
assert!(stroke(&[Vec2::new(f64::NAN, 0.0)], 1.0, EndStyle::Round, JoinStyle::Round).is_empty()); assert!(stroke(&[Vec2::new(f64::NAN, 0.0)], 1.0, EndStyle::Round, JoinStyle::Round).is_empty());
} }
/// Three 10-unit lines and a filled triangle 0.5 mm wide at 1 mm per unit, printed with `pens`.
fn styled(pens: [Pen; 4]) -> DisplayList {
let prim = |kind, start, len| crate::DPrim {
handle: cadcraft_doc::Handle(1),
color: cadcraft_color::Rgb(255, 0, 0),
aci7: false,
lw: 0.5,
transparency: 0,
kind,
start,
len,
};
DisplayList {
verts: (0..3).flat_map(|k| [Vec2::new(0.0, 5.0 * f64::from(k)), Vec2::new(10.0, 5.0 * f64::from(k))]).collect(),
tris: vec![Vec2::new(0.0, 20.0), Vec2::new(10.0, 20.0), Vec2::new(0.0, 30.0)],
prims: vec![prim(Kind::Polyline, 0, 2), prim(Kind::Polyline, 2, 2), prim(Kind::Polyline, 4, 2), prim(Kind::Tris, 0, 3)],
pens: pens.to_vec(),
..Default::default()
}
}
#[test]
fn styled_geometry_stops_at_the_lists_point_limit_and_says_so() {
// Made after the build, outside its budgets: a 2-point line with round ends becomes 78
// triangle corners, so a list near the point budget passed it (#1603).
let points = |l: &DisplayList| l.verts.len() + l.tris.len();
let round = Pen { end: EndStyle::Round, ..Pen::default() };
let butt = Pen { end: EndStyle::Butt, ..Pen::default() };
let built = styled([round, round, butt, Pen::default()]);
let mut all = built.clone();
apply_within(&mut all, 1.0, usize::MAX);
assert!(all.prims.iter().all(|p| p.kind == Kind::Tris) && all.prims[..3] != built.prims[..3] && !all.truncated);
let first = all.points(&all.prims[0]).len();
let last = all.points(&all.prims[2]).len();
assert!(last < first, "the butt-ended line is the smaller outline");
// Room for the first round-ended outline, and then none, or enough for the butt-ended third
// line's outline only: the second doesn't fit, so it and every primitive after it, the
// third included, keep their plain line.
for extra in [0, last] {
let max = points(&built) + first + extra;
let mut cut = built.clone();
apply_within(&mut cut, 1.0, max);
assert!(cut.truncated && points(&cut) <= max, "{extra}: {} points", points(&cut));
assert_eq!(cut.prims[0], all.prims[0], "{extra}: the outline that fits is drawn");
assert_eq!(cut.prims[1..], built.prims[1..], "{extra}");
assert!(cut.pens.is_empty(), "{extra}: the pens are used up");
}
// A fill pattern without room stays a solid fill.
let checker = Pen { fill: FillStyle::Checkerboard, ..Pen::default() };
let built = styled([Pen::default(), Pen::default(), Pen::default(), checker]);
let mut all = built.clone();
apply_within(&mut all, 1.0, usize::MAX);
assert!(points(&all) > points(&built) + 3 && all.prims[3] != built.prims[3] && !all.truncated);
let mut cut = built.clone();
apply_within(&mut cut, 1.0, points(&built) + 3);
assert!(cut.truncated && cut.prims == built.prims && points(&cut) == points(&built));
}
#[test]
fn a_fill_past_the_point_limit_says_so_though_a_later_triangle_runs_out_of_cells() {
// A fill whose pattern passes the point limit on one triangle is refused for that: the
// list is marked and applying stops, even when a later triangle would take more pattern
// cells than are left. So the butt-ended line after it keeps its plain line, though its
// outline would fit.
let points = |l: &DisplayList| l.verts.len() + l.tris.len();
let butt = Pen { end: EndStyle::Butt, ..Pen::default() };
let checker = Pen { fill: FillStyle::Checkerboard, ..Pen::default() };
let mut lines = styled([Pen::default(), Pen::default(), butt, Pen::default()]);
apply_within(&mut lines, 1.0, usize::MAX);
let outline = lines.points(&lines.prims[2]).len();
// The fill moved before the third line, with a second triangle far too large to pattern.
let mut built = styled([Pen::default(), Pen::default(), checker, butt]);
built.prims.swap(2, 3);
built.tris.extend([Vec2::new(0.0, 0.0), Vec2::new(1e9, 0.0), Vec2::new(0.0, 1e9)]);
built.prims[2].len = 6;
let mut cells = MAX_PATTERN_CELLS;
assert!(pattern(&built.tris[..3], FillStyle::Checkerboard, PATTERN_MM, &mut cells).is_some_and(|p| p.len() > outline));
assert!(pattern(&built.tris[3..], FillStyle::Checkerboard, PATTERN_MM, &mut cells).is_none());
let max = points(&built) + outline;
let mut cut = built.clone();
apply_within(&mut cut, 1.0, max);
assert!(cut.truncated, "the fill past the limit marks the list");
assert_eq!(cut.prims, built.prims, "the fill stays solid and the line after it plain");
assert!(points(&cut) == points(&built) && cut.pens.is_empty());
// The cells running out first keeps the fill solid without marking the list, as before,
// and the line after it is drawn with its ends.
let mut first = built.clone();
first.tris.rotate_left(3);
apply_within(&mut first, 1.0, max);
assert!(!first.truncated && first.prims[2] == built.prims[2] && first.prims[3].kind == Kind::Tris);
}
} }
+21 -50
View File
@@ -1,9 +1,11 @@
#[cfg(not(target_arch = "wasm32"))]
use super::display::append;
use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT};
use super::draw::entity; use super::draw::entity;
use super::viewports::{MAX_VIEWPORTS, viewport}; use super::viewports::{MAX_VIEWPORTS, viewport};
use super::{ use super::{
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Fade, Handle, Lineweight, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper,
Mat3, Space, Vec2, paper, pen, plotstyle, point, pen, plotstyle, point,
}; };
/// Build options. /// Build options.
@@ -96,7 +98,6 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St
depth: 0, depth: 0,
top, top,
frozen, frozen,
selecting: false,
vp_colors, vp_colors,
lt_factor: 1.0, lt_factor: 1.0,
block_pstyle: None, block_pstyle: None,
@@ -106,26 +107,16 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St
} }
fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList { fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList {
build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS) build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS)
} }
/// [`build_space`] holding at most `max_points` points and `max_prims` primitives, and laying out /// [`build_space`] holding at most `max_points` points and laying out at most `max_dashes` dash
/// at most `max_dashes` dash pattern elements. /// pattern elements.
pub(crate) fn build_space_within( pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plotting: bool, max_points: usize, max_dashes: usize) -> DisplayList {
d: &Drawing,
space: &Space,
opts: &Options,
plotting: bool,
max_points: usize,
max_prims: usize,
max_dashes: usize,
) -> DisplayList {
let opts = &with_point_view(d, space, opts); let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t)); let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t));
let (points, prims, dashes) = let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
(std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let loops = std::sync::OnceLock::new(); let loops = std::sync::OnceLock::new();
let fade = Fade::of(d);
let mut b = Builder { let mut b = Builder {
list: DisplayList::default(), list: DisplayList::default(),
opts, opts,
@@ -136,12 +127,9 @@ pub(crate) fn build_space_within(
transparency: 0, transparency: 0,
points: &points, points: &points,
max_points, max_points,
prims: &prims,
max_prims,
dashes: &dashes, dashes: &dashes,
max_dashes, max_dashes,
loops: &loops, loops: &loops,
fade: fade.as_ref(),
}; };
if let Space::Paper(name) = space { if let Space::Paper(name) = space {
b.list.sheet = paper::sheet(d, name); b.list.sheet = paper::sheet(d, name);
@@ -170,7 +158,7 @@ pub(crate) fn build_space_within(
} }
// A layout is drawn in paper units, so its pens become geometry now. // A layout is drawn in paper units, so its pens become geometry now.
if let Some(sheet) = b.list.sheet { if let Some(sheet) = b.list.sheet {
pen::apply_within(&mut b.list, sheet.unit_mm, b.max_points); pen::apply(&mut b.list, sheet.unit_mm);
} }
b.list b.list
} }
@@ -189,8 +177,8 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
use rayon::prelude::*; use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = store.iter().collect(); let ents: Vec<&std::sync::Arc<Entity>> = store.iter().collect();
let budget = std::sync::atomic::AtomicUsize::new(0); let budget = std::sync::atomic::AtomicUsize::new(0);
let (opts, plotting, points, max_points, prims, max_prims, dashes, max_dashes, loops, fade) = let (opts, plotting, points, max_points, dashes, max_dashes, loops) =
(b.opts, b.plotting, b.points, b.max_points, b.prims, b.max_prims, b.dashes, b.max_dashes, b.loops, b.fade); (b.opts, b.plotting, b.points, b.max_points, b.dashes, b.max_dashes, b.loops);
let parts: Vec<DisplayList> = ents let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK) .par_chunks(PARALLEL_CHUNK)
.map(|chunk| { .map(|chunk| {
@@ -204,12 +192,9 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
transparency: 0, transparency: 0,
points, points,
max_points, max_points,
prims,
max_prims,
dashes, dashes,
max_dashes, max_dashes,
loops, loops,
fade,
}; };
for e in chunk { for e in chunk {
entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
@@ -217,11 +202,13 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
part.list part.list
}) })
.collect(); .collect();
// One allocation per array for the joined list, within what it may hold. // One allocation per array for the joined list.
b.list.prims.reserve(parts.iter().map(|p| p.prims.len()).sum::<usize>().min(b.max_prims)); b.list.prims.reserve(parts.iter().map(|p| p.prims.len()).sum());
b.list.verts.reserve(parts.iter().map(|p| p.verts.len()).sum::<usize>().min(b.max_points)); b.list.verts.reserve(parts.iter().map(|p| p.verts.len()).sum());
b.list.tris.reserve(parts.iter().map(|p| p.tris.len()).sum::<usize>().min(b.max_points)); b.list.tris.reserve(parts.iter().map(|p| p.tris.len()).sum());
b.join(parts); for part in parts {
append(&mut b.list, part);
}
} }
/// The plot style table a build draws with: the one in `opts`, else (on screen) the layout's /// The plot style table a build draws with: the one in `opts`, else (on screen) the layout's
@@ -251,17 +238,6 @@ pub(crate) fn with_point_view(d: &Drawing, space: &Space, opts: &Options) -> Opt
/// Build the display list for a set of loose entities (previews, rubber bands). /// Build the display list for a set of loose entities (previews, rubber bands).
pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents: I, opts: &Options) -> DisplayList { pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents: I, opts: &Options) -> DisplayList {
build_entities_in_viewport(d, ents, opts, &[])
}
/// [`build_entities`] as a selection through a layout viewport that freezes the layers in
/// `frozen` sees them: what is on one of those layers is left out, as the viewport does not draw
/// it, the parts of a block reference too. Only a point on the layer Defpoints that is a part of
/// a block is kept, as the definition points of a dimension are in its block: a selection counts
/// it whatever the viewport freezes ([`cadcraft_doc::point_on_defpoints`]). Picking through the
/// viewport tests objects against this, so a part the viewport does not draw is not hit, and the
/// highlight of an object seen through the viewport is built from it.
pub fn build_entities_in_viewport<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents: I, opts: &Options, frozen: &[String]) -> DisplayList {
let ents: Vec<&Entity> = ents.into_iter().collect(); let ents: Vec<&Entity> = ents.into_iter().collect();
// Only previews holding points need the model extents for relative point sizes. // Only previews holding points need the model extents for relative point sizes.
let with_view; let with_view;
@@ -271,10 +247,8 @@ pub fn build_entities_in_viewport<'a, I: IntoIterator<Item = &'a Entity>>(d: &Dr
} else { } else {
opts opts
}; };
let (points, prims, dashes) = let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
(std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let loops = std::sync::OnceLock::new(); let loops = std::sync::OnceLock::new();
let fade = Fade::of(d);
let mut b = Builder { let mut b = Builder {
list: DisplayList::default(), list: DisplayList::default(),
opts, opts,
@@ -285,15 +259,12 @@ pub fn build_entities_in_viewport<'a, I: IntoIterator<Item = &'a Entity>>(d: &Dr
transparency: 0, transparency: 0,
points: &points, points: &points,
max_points: MAX_DISPLAY_POINTS, max_points: MAX_DISPLAY_POINTS,
prims: &prims,
max_prims: MAX_DISPLAY_PRIMS,
dashes: &dashes, dashes: &dashes,
max_dashes: MAX_DASH_ELEMENTS, max_dashes: MAX_DASH_ELEMENTS,
loops: &loops, loops: &loops,
fade: fade.as_ref(),
}; };
for e in ents { for e in ents {
entity(&mut b, &Ctx { selecting: true, ..top_ctx(d, Mat3::IDENTITY, e.handle, frozen, &[]) }, e); entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
} }
b.list b.list
} }
+2 -10
View File
@@ -6,25 +6,17 @@ use super::{Color, Ctx, Drawing, Entity, Ink, Lineweight, ink};
type Resolved = (Ink, f32, Option<cadcraft_doc::Linetype>, f64, bool, u8, u8); type Resolved = (Ink, f32, Option<cadcraft_doc::Linetype>, f64, bool, u8, u8);
pub(crate) fn resolve(ctx: &Ctx, e: &Entity, plotting: bool) -> Resolved { pub(crate) fn resolve(ctx: &Ctx, e: &Entity, plotting: bool) -> Resolved {
// A selection through a viewport counts a point on Defpoints inside a block whatever the resolve_common(ctx, &e.common, plotting)
// viewport freezes.
let kept = ctx.selecting && ctx.depth > 0 && cadcraft_doc::point_on_defpoints(e);
resolve_in(ctx, &e.common, plotting, if kept { &[] } else { ctx.frozen })
} }
/// [`resolve`] for an object's properties `c`. /// [`resolve`] for an object's properties `c`.
pub(crate) fn resolve_common(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool) -> Resolved { pub(crate) fn resolve_common(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool) -> Resolved {
resolve_in(ctx, c, plotting, ctx.frozen)
}
/// [`resolve_common`] with `frozen` as the layers the viewport leaves out.
fn resolve_in(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool, frozen: &[String]) -> Resolved {
let d = ctx.d; let d = ctx.d;
// Layer "0" inside a block takes the insert's layer. // Layer "0" inside a block takes the insert's layer.
let layer_name = if c.layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { c.layer.as_str() }; let layer_name = if c.layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { c.layer.as_str() };
let layer = d.layer(layer_name); let layer = d.layer(layer_name);
let visible = let visible =
c.visible && layer.is_none_or(|l| l.visible() && (!plotting || l.plot)) && !frozen.iter().any(|f| f.eq_ignore_ascii_case(layer_name)); c.visible && layer.is_none_or(|l| l.visible() && (!plotting || l.plot)) && !ctx.frozen.iter().any(|f| f.eq_ignore_ascii_case(layer_name));
let layer_color = ctx.layer_color(layer_name).unwrap_or(Color::Index(7)); let layer_color = ctx.layer_color(layer_name).unwrap_or(Color::Index(7));
let rgb = ink(c.color, layer_color, ctx.block_color); let rgb = ink(c.color, layer_color, ctx.block_color);
let lw = match c.lineweight { let lw = match c.lineweight {
+10 -103
View File
@@ -38,8 +38,6 @@ pub struct TableText {
/// MTEXT attachment (1 top left … 9 bottom right). /// MTEXT attachment (1 top left … 9 bottom right).
pub attach: u8, pub attach: u8,
pub height: f64, pub height: f64,
/// Available horizontal text wrap width inside the cell (0 disables wrapping).
pub wrap_width: f64,
pub color: Color, pub color: Color,
pub style: String, pub style: String,
pub text: String, pub text: String,
@@ -365,17 +363,12 @@ fn layout(d: &Drawing, t: &Table) -> TableGeom {
1 => (y0 + y1) / 2.0, 1 => (y0 + y1) / 2.0,
_ => y1 - cs.margin_v, _ => y1 - cs.margin_v,
}; };
// Why: wrap cell text inside the cell's horizontal bounds (excluding margins) so long lines
// do not spill into adjacent columns; clamp non-finite or narrow spans to 0 (no wrap).
let inner_w = x1 - x0 - 2.0 * cs.margin_h;
let wrap_width = if inner_w.is_finite() && inner_w > 0.0 { inner_w } else { 0.0 };
g.texts.push(TableText { g.texts.push(TableText {
row: a.row, row: a.row,
col: a.col, col: a.col,
at: p(x, y), at: p(x, y),
attach, attach,
height: cell.text_height.filter(|h| h.is_finite() && *h > 0.0).map_or(cs.text_height, |h| h * k), height: cell.text_height.filter(|h| h.is_finite() && *h > 0.0).map_or(cs.text_height, |h| h * k),
wrap_width,
color: cs.text_color, color: cs.text_color,
style: cs.text_style.clone(), style: cs.text_style.clone(),
text: cell.text.clone(), text: cell.text.clone(),
@@ -392,28 +385,6 @@ fn style_ink(c: Color, table: Ink) -> Ink {
} }
} }
/// Resolve the [`cadcraft_fonts::MTextParams`] the renderer uses for a table cell's text style,
/// alignment point, text height, attachment, and horizontal wrap width.
pub fn table_text_mtext_params(d: &Drawing, style: &str, at: Vec2, height: f64, attach: u8, wrap_width: f64) -> cadcraft_fonts::MTextParams {
let ts = crate::text_style(d, style);
let font = crate::style_font(&ts);
cadcraft_fonts::MTextParams {
attach,
width: wrap_width,
font,
width_factor: ts.width_factor,
oblique: ts.oblique,
..cadcraft_fonts::MTextParams::new(at, height)
}
}
/// Lay out a [`TableText`] with the exact resolved text style, font, width factor, and oblique
/// angle used when drawing the table.
pub fn layout_table_text(d: &Drawing, tx: &TableText) -> cadcraft_fonts::MTextLayout {
let mp = table_text_mtext_params(d, &tx.style, tx.at, tx.height, tx.attach, tx.wrap_width);
cadcraft_fonts::layout_mtext_with(&tx.text, &mp)
}
/// Draw a table into the display list. /// Draw a table into the display list.
pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) {
let g = table_geometry(ctx.d, t); let g = table_geometry(ctx.d, t);
@@ -435,9 +406,18 @@ pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) {
return; return;
} }
for tx in &g.texts { for tx in &g.texts {
let ts = crate::text_style(ctx.d, &tx.style);
let font = crate::style_font(&ts);
// Cell content is MTEXT (`\P`, `{\Q15;…}`, `\F…;`): laid out as such, at the cell's // Cell content is MTEXT (`\P`, `{\Q15;…}`, `\F…;`): laid out as such, at the cell's
// alignment point (its numbering is MTEXT's attachment). // alignment point (its numbering is MTEXT's attachment).
let layout = layout_table_text(ctx.d, tx); let mp = cadcraft_fonts::MTextParams {
attach: tx.attach,
font,
width_factor: ts.width_factor,
oblique: ts.oblique,
..cadcraft_fonts::MTextParams::new(tx.at, tx.height)
};
let layout = cadcraft_fonts::layout_mtext_with(&tx.text, &mp);
for piece in &layout.pieces { for piece in &layout.pieces {
b.shaped(ctx, style_ink(tx.color, rgb), lw, &piece.shaped); b.shaped(ctx, style_ink(tx.color, rgb), lw, &piece.shaped);
} }
@@ -478,77 +458,4 @@ mod budget_tests {
let part = part_table(&t, &rows, Vec2::ZERO); let part = part_table(&t, &rows, Vec2::ZERO);
assert_eq!(part.cells[0][0].merged, Some((99, 1))); assert_eq!(part.cells[0][0].merged, Some((99, 1)));
} }
#[test]
fn cell_text_wraps_within_column_and_merged_bounds() {
let mut d = Drawing::default();
let long_text = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let t = Table {
col_widths: vec![30.0, 20.0],
row_heights: vec![40.0, 40.0],
text_height: 2.5,
cells: vec![
vec![TableCell { text: long_text.into(), ..Default::default() }, TableCell { text: "B".into(), ..Default::default() }],
vec![TableCell { text: long_text.into(), merged: Some((1, 2)), ..Default::default() }, TableCell::default()],
],
..Default::default()
};
let g = table_geometry(&d, &t);
assert!(g.texts[0].wrap_width > 0.0 && g.texts[0].wrap_width < 30.0);
// Merged cell spans both columns (50.0 total), so its wrap width exceeds a single column.
assert!(g.texts[2].wrap_width > g.texts[0].wrap_width);
// Render via `crate::build` and verify all stroke vertices of cell (0,0) stay inside column 0 [0, 30].
d.model.push(cadcraft_doc::Entity::new(
cadcraft_doc::Handle(1),
cadcraft_doc::EntityKind::Table(Table {
col_widths: vec![30.0, 20.0],
row_heights: vec![40.0],
text_height: 2.5,
cells: vec![vec![TableCell { text: long_text.into(), ..Default::default() }, TableCell::default()]],
..Default::default()
}),
));
let list = crate::build(&d, &cadcraft_doc::Space::Model, &crate::Options::default());
assert!(!list.verts.is_empty());
for p in &list.verts {
assert!(p.x >= -1e-6 && p.x <= 50.0 + 1e-6, "vertex outside table: {p:?}");
}
// Verify layout_mtext_with at tx.wrap_width wraps into multiple lines and stays inside column 0 [0, 30].
let mp = cadcraft_fonts::MTextParams {
attach: g.texts[0].attach,
width: g.texts[0].wrap_width,
..cadcraft_fonts::MTextParams::new(g.texts[0].at, g.texts[0].height)
};
let laid = cadcraft_fonts::layout_mtext_with(&g.texts[0].text, &mp);
assert!(laid.lines.len() > 1);
for s in &laid.strokes {
for p in s {
assert!(p.x >= -1e-6 && p.x <= 30.0 + 1e-6, "glyph spilled past column 0: {p:?}");
}
}
}
#[test]
fn narrow_or_non_finite_columns_and_escapes_do_not_panic() {
let mut d = Drawing::default();
let t = Table {
col_widths: vec![0.1, f64::NAN, 40.0],
row_heights: vec![10.0],
cells: vec![vec![
TableCell { text: "Narrow".into(), ..Default::default() },
TableCell { text: "NaN".into(), ..Default::default() },
TableCell { text: "Line1\\PLine2\\\\{brace}".into(), ..Default::default() },
]],
..Default::default()
};
let g = table_geometry(&d, &t);
assert_eq!(g.texts[0].wrap_width, 0.0);
assert_eq!(g.texts[1].wrap_width, 0.0);
assert!(g.texts[2].wrap_width > 0.0);
d.model.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), cadcraft_doc::EntityKind::Table(t)));
let list = crate::build(&d, &cadcraft_doc::Space::Model, &crate::Options::default());
assert!(!list.verts.is_empty());
}
} }
+8 -581
View File
@@ -39,129 +39,6 @@ fn linetype_dashes_line() {
assert!(l.prims.len() > 10); assert!(l.prims.len() > 10);
} }
/// Loose entities built as a layout viewport draws them leave out what is on a layer frozen in
/// it, the part of a block reference on that layer too, whatever the case of the layer's name.
/// With no such layer the list is the one [`build_entities`] gives.
#[test]
fn loose_entities_built_for_a_viewport_leave_out_its_frozen_layers() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = cadcraft_doc::Entity::new(Handle(handle), kind);
e.common.layer = layer.into();
e
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut b = cadcraft_doc::Block::new("B");
for part in [line(1, 0.0, "0"), line(2, 5.0, "Hidden")] {
b.entities.push(part);
}
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let reference = cadcraft_doc::Insert { block: "B".into(), ..Default::default() };
let ents = [cadcraft_doc::Entity::new(Handle(3), EntityKind::Insert(reference)), line(4, 5.0, "Hidden"), line(5, 8.0, "0")];
let ys = |l: &DisplayList| -> Vec<f64> { l.prims.iter().map(|p| l.points(p)[0].y).collect() };
let opts = Options::default();
let frozen = ["HIDDEN".to_string()];
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 8.0]);
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 5.0, 8.0]);
assert_eq!(ys(&build_entities(&d, &ents, &opts)), [0.0, 5.0, 5.0, 8.0]);
}
/// A drawing with the layers Defpoints and "Hidden" and the block P: a line along y = 0 on layer
/// 0, a point at y = 5 and a line along y = 6 on Defpoints, and a line along y = 7 on "Hidden".
/// The block N holds a dimension that draws P ([`dimension_of_p`]).
fn drawing_with_p() -> Drawing {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = cadcraft_doc::Entity::new(Handle(handle), kind);
e.common.layer = layer.into();
e
};
let mut point = cadcraft_doc::Entity::new(Handle(2), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 }));
point.common.layer = "Defpoints".into();
let mut d = Drawing::new_metric();
d.ensure_layer("Defpoints");
d.ensure_layer("Hidden");
let mut p = cadcraft_doc::Block::new("P");
for part in [line(1, 0.0, "0"), point, line(3, 6.0, "Defpoints"), line(4, 7.0, "Hidden")] {
p.entities.push(part);
}
d.blocks.insert("P".into(), std::sync::Arc::new(p));
let mut n = cadcraft_doc::Block::new("N");
n.entities.push(cadcraft_doc::Entity::new(Handle(1), dimension_of_p()));
d.blocks.insert("N".into(), std::sync::Arc::new(n));
d
}
/// A dimension that draws the block P of [`drawing_with_p`].
fn dimension_of_p() -> EntityKind {
EntityKind::Dimension(cadcraft_doc::Dimension {
kind: cadcraft_doc::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some("P".into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
})
}
/// Built for a selection through a viewport that freezes the layer Defpoints, a point on that
/// layer that is a part of a block is kept: in the block a dimension draws, where its definition
/// points are, in that of a dimension inside a block and in that of a plain reference. The line
/// on Defpoints in the same block is left out, in a dimension too, like the line on the other
/// frozen layer. A point on Defpoints that is not a part of a block is left out with its layer,
/// like every object on a layer the viewport freezes: the rule is about the parts of blocks.
#[test]
fn entities_built_for_a_viewport_keep_the_points_on_defpoints_in_a_block() {
let d = drawing_with_p();
let reference = |handle: u64, block: &str| {
cadcraft_doc::Entity::new(Handle(handle), EntityKind::Insert(cadcraft_doc::Insert { block: block.into(), ..Default::default() }))
};
let mut loose = cadcraft_doc::Entity::new(Handle(7), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 9.0, 0.0), angle: 0.0 }));
loose.common.layer = "Defpoints".into();
let ents = [cadcraft_doc::Entity::new(Handle(4), dimension_of_p()), reference(5, "N"), reference(6, "P"), loose];
let ys = |l: &DisplayList| -> Vec<f64> { l.prims.iter().map(|p| l.points(p)[0].y).collect() };
let opts = Options::default();
let frozen = ["defpoints".to_string(), "Hidden".to_string()];
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 5.0, 0.0, 5.0, 0.0, 5.0]);
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 6.0, 7.0, 0.0, 5.0, 6.0, 7.0, 0.0, 5.0, 6.0, 7.0, 9.0]);
}
/// A layout viewport that freezes the layer Defpoints does not draw the points on it, a part of a
/// dimension's block or of a reference's: only a selection through the viewport counts them
/// ([`build_entities_in_viewport`]). A viewport that draws the layer draws them.
#[test]
fn a_viewport_that_freezes_defpoints_does_not_draw_the_points_on_it() {
let drawn = |frozen: &[&str]| -> Vec<f64> {
let mut d = drawing_with_p();
d.add(&Space::Model, Common::default(), dimension_of_p()).unwrap();
let held = cadcraft_doc::Insert { block: "N".into(), insert: Vec3::new(0.0, 10.0, 0.0), ..Default::default() };
d.add(&Space::Model, Common::default(), EntityKind::Insert(held)).unwrap();
let plain = cadcraft_doc::Insert { block: "P".into(), insert: Vec3::new(0.0, 20.0, 0.0), ..Default::default() };
d.add(&Space::Model, Common::default(), EntityKind::Insert(plain)).unwrap();
// The viewport shows model space at 1:1 around (5, 15), so paper and model coordinates
// are the same.
let mut v = vp(Vec2::new(5.0, 15.0), 60.0, 60.0, Vec2::new(5.0, 15.0), 60.0, 2);
v.frozen_layers = frozen.iter().map(|layer| layer.to_string()).collect();
let paper = Space::Paper("Layout1".into());
d.add(&paper, Common::default(), EntityKind::Viewport(v)).unwrap();
viewport_points(&build(&d, &paper, &Options::default())).iter().map(|p| p[0].y).collect()
};
assert_eq!(drawn(&["defpoints"]), [0.0, 7.0, 10.0, 17.0, 20.0, 27.0]);
assert_eq!(drawn(&[]), [0.0, 5.0, 6.0, 7.0, 10.0, 15.0, 16.0, 17.0, 20.0, 25.0, 26.0, 27.0]);
}
#[test] #[test]
fn frozen_layer_hidden() { fn frozen_layer_hidden() {
let mut d = sample(); let mut d = sample();
@@ -193,76 +70,6 @@ fn text_produces_strokes() {
assert!(l.prims.len() >= 3); assert!(l.prims.len() >= 3);
} }
/// What is drawn of one TEXT whose two points are `span` apart, and the drawing's extents.
fn drawn_and_extents(
halign: cadcraft_doc::HAlign,
value: &str,
height: f64,
width_factor: f64,
span: f64,
) -> (cadcraft_geom::Bounds2, cadcraft_geom::Bounds2) {
let mut d = Drawing::new_imperial();
let text = cadcraft_doc::Text {
insert: Vec3::ZERO,
align_pt: Some(Vec3::new(span, 0.0, 0.0)),
height,
value: value.into(),
rotation: 0.0,
width_factor,
oblique: 0.0,
style: "Standard".into(),
halign,
valign: Default::default(),
};
d.add(&Space::Model, Common::default(), EntityKind::Text(text)).unwrap();
let l = build(&d, &Space::Model, &Options::default());
let drawn = cadcraft_geom::Bounds2::from_points(l.prims.iter().flat_map(|p| l.points(p).iter().copied()));
assert!(!drawn.is_empty(), "{value:?} over {span}: the text is drawn");
(drawn, d.extents(&Space::Model))
}
/// Fit text whose two points are so close that the fitted width factor is too small to shape
/// is drawn unstretched, far wider than the span between its points: the drawing's extents hold
/// what is drawn, as they do for the same text fitted over a span it can be stretched to.
#[test]
fn fit_text_extents_hold_the_drawn_text_when_the_span_is_too_short_to_fit() {
for span in [1e-7, 10.0] {
let (drawn, extents) = drawn_and_extents(cadcraft_doc::HAlign::Fit, "AB", 1.0, 1.0, span);
let slack = 1e-6;
assert!(
drawn.min.x >= extents.min.x - slack
&& drawn.max.x <= extents.max.x + slack
&& drawn.min.y >= extents.min.y - slack
&& drawn.max.y <= extents.max.y + slack,
"span {span}: drawn {drawn:?} outside extents {extents:?}"
);
}
// The short span is the case the fitted factor falls back in: the text is wider than its span.
assert!(drawn_and_extents(cadcraft_doc::HAlign::Fit, "AB", 1.0, 1.0, 1e-7).0.width() > 1e-7 * 1000.0);
}
/// The extents estimate a line's width where the fonts measure it, so near the fonts' cutoffs
/// the two could decide differently. The extents then take the larger outcome, and stay near
/// what is drawn in each of these cases.
#[test]
fn aligned_and_fit_text_extents_stay_near_the_drawn_text_at_the_cutoffs() {
use cadcraft_doc::HAlign::{Aligned, Fit};
// Wide letters over a span just where the fitted factor reaches the cutoff: the estimate says
// the text is stretched, the fonts draw it unstretched, a million times wider than its span.
let (drawn, extents) = drawn_and_extents(Fit, "AAAAAAAAA", 1.0, 1.0, 8.12e-6);
assert!(drawn.width() > 1.0, "drawn unstretched: {drawn:?}");
assert!(extents.width() > drawn.width() * 0.9, "drawn {drawn:?}, extents {extents:?}");
// A narrow letter shrunk into a short span by Aligned stays about as tall as it was.
let (drawn, extents) = drawn_and_extents(Aligned, "I", 1.0, 1.0, 1.0 / 3.0);
assert!(extents.max.y >= drawn.max.y - 1e-6, "drawn {drawn:?}, extents {extents:?}");
// A line of next to no width is left as it is: the extents do not reach for the second point.
for halign in [Aligned, Fit] {
let (drawn, extents) = drawn_and_extents(halign, "I", 1e-8, 1e-5, 10.0);
assert!(drawn.width() < 1e-3 && drawn.height() < 1e-3, "{halign:?}: drawn as it is: {drawn:?}");
assert!(extents.width() < 1e-3 && extents.height() < 1e-3, "{halign:?}: extents {extents:?}");
}
}
#[test] #[test]
fn hatch_pattern_and_solid() { fn hatch_pattern_and_solid() {
let mut d = Drawing::new_imperial(); let mut d = Drawing::new_imperial();
@@ -1716,7 +1523,7 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
assert_eq!(loops_of(&h).len(), 2); assert_eq!(loops_of(&h).len(), 2);
} }
// ---------- point and primitive budgets (#1922, #1603) ---------- // ---------- point budget (#1922) ----------
fn circle() -> EntityKind { fn circle() -> EntityKind {
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::ZERO, radius: 100.0 }) EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::ZERO, radius: 100.0 })
@@ -1744,15 +1551,7 @@ fn block_copies_stop_at_the_point_budget_and_say_so() {
let d = arrayed_circles(); let d = arrayed_circles();
let full = build(&d, &Space::Model, &Options::default()); let full = build(&d, &Space::Model, &Options::default());
assert!(!full.truncated && points(&full) > 100_000, "{}", points(&full)); assert!(!full.truncated && points(&full) > 100_000, "{}", points(&full));
let l = crate::pipeline::build_space_within( let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS);
&d,
&Space::Model,
&Options::default(),
false,
10_000,
crate::MAX_DISPLAY_PRIMS,
crate::MAX_DASH_ELEMENTS,
);
assert!(l.truncated); assert!(l.truncated);
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l)); assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
assert!(l.prims.iter().all(|p| p.start as usize + p.len as usize <= l.verts.len())); assert!(l.prims.iter().all(|p| p.start as usize + p.len as usize <= l.verts.len()));
@@ -1765,336 +1564,11 @@ fn objects_built_on_all_cores_stop_at_the_point_budget_and_say_so() {
for _ in 0..600 { for _ in 0..600 {
d.add(&Space::Model, Common::default(), circle()).unwrap(); d.add(&Space::Model, Common::default(), circle()).unwrap();
} }
let l = crate::pipeline::build_space_within( let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS);
&d,
&Space::Model,
&Options::default(),
false,
10_000,
crate::MAX_DISPLAY_PRIMS,
crate::MAX_DASH_ELEMENTS,
);
assert!(l.truncated); assert!(l.truncated);
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l)); assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
} }
fn point_at(x: f64) -> EntityKind {
EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(x, 0.0, 0.0), angle: 0.0 })
}
/// A block of one point referenced as 1,000 copies in place: every copy is one primitive of one
/// point, so the point budget holds far more of them than a 32-bit target's primitive vector
/// (#1603).
fn arrayed_points() -> Drawing {
let mut d = Drawing::new_imperial();
let mut blk = cadcraft_doc::Block::new("B");
blk.entities.push(block_entity(1, Common::default(), point_at(0.0)));
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
ins.cols = 1000;
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
d
}
#[test]
fn one_point_primitives_stop_at_the_primitive_budget_and_say_so() {
let d = arrayed_points();
let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
assert!(!full.truncated && full.prims.len() >= 1000, "{}", full.prims.len());
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 100, MAX_DASH_ELEMENTS);
assert!(l.truncated);
assert!(!l.prims.is_empty() && l.prims.len() <= 100, "{}", l.prims.len());
// And the copies past it are not visited.
assert!(l.expanded < full.expanded / 2, "{} of {}", l.expanded, full.expanded);
}
#[test]
fn primitives_built_on_all_cores_stop_at_the_primitive_budget_and_say_so() {
// Enough references of a one-point block for the parallel build: the parts share one
// primitive count, and stop visiting their blocks once it is spent.
let mut d = Drawing::new_imperial();
let mut blk = cadcraft_doc::Block::new("B");
blk.entities.push(block_entity(1, Common::default(), point_at(0.0)));
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
for i in 0..600 {
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
ins.insert = Vec3::new(f64::from(i), 0.0, 0.0);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
}
let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
assert_eq!(full.prims.len(), 600);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 100, MAX_DASH_ELEMENTS);
assert!(l.truncated);
assert!(!l.prims.is_empty() && l.prims.len() <= 100, "{}", l.prims.len());
assert!(l.expanded < full.expanded / 2, "{} of {}", l.expanded, full.expanded);
// A limit no one part reaches (parts of 256 objects): only the shared count stops the parts
// at the limit together. Counted per part, each would build its whole chunk, and the join
// would keep the first part alone.
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 300, MAX_DASH_ELEMENTS);
assert!(l.truncated);
assert_eq!(l.prims.len(), 300);
}
/// A polyline of 200 points zigzagging across y = 1 between x = 1.5 and 8.5: a clip whose edge
/// is y = 1 cuts it into about 100 pieces of three points each.
fn zigzag() -> EntityKind {
let vertices = (0..200).map(|i| PolyVertex::new(Vec2::new(1.5 + 7.0 * f64::from(i) / 199.0, if i % 2 == 0 { 0.0 } else { 2.0 }))).collect();
EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false })
}
#[test]
fn pieces_cut_by_a_clip_stop_at_the_list_limits_and_say_so() {
// Seen through a viewport whose model window starts at y = 1, the zigzag and then a point
// inside the window. Each drawing ends with a point the budgets alone would still take after
// the pieces: a full list stops the build.
let mut through_viewport = Drawing::new_imperial();
through_viewport.add(&Space::Model, Common::default(), zigzag()).unwrap();
through_viewport
.add(&Space::Model, Common::default(), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 }))
.unwrap();
let paper = Space::Paper("Layout1".into());
through_viewport.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap();
through_viewport.add(&paper, Common::default(), point_at(5.0)).unwrap();
// In a block reference clipped (XCLIP) to a rectangle from y = 1 up, without its frame.
let mut xclipped = Drawing::new_imperial();
xclipped.header.set_i64("XCLIPFRAME", 0);
let mut blk = cadcraft_doc::Block::new("Z");
blk.entities.push(block_entity(1, Common::default(), zigzag()));
blk.entities.push(block_entity(2, Common::default(), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 })));
xclipped.blocks.insert("Z".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = insert_of("Z") else { panic!("an insert") };
ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(0.0, 1.0), Vec2::new(10.0, 10.0)]));
xclipped.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
xclipped.add(&Space::Model, Common::default(), point_at(5.0)).unwrap();
for (d, space) in [(&through_viewport, &paper), (&xclipped, &Space::Model)] {
let build = |max_points, max_prims| {
crate::pipeline::build_space_within(d, space, &Options::default(), false, max_points, max_prims, MAX_DASH_ELEMENTS)
};
// The one polyline the build charges becomes many pieces with more points.
let full = build(MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS);
assert!(!full.truncated && full.prims.len() > 50 && points(&full) > 250, "{space:?}: {} prims, {} points", full.prims.len(), points(&full));
let l = build(10_000, 20);
assert!(l.truncated && !l.prims.is_empty() && l.prims.len() <= 20, "{space:?}: {}", l.prims.len());
// The pieces stop at the first that doesn't fit: neither point comes after them.
let l = build(220, MAX_DISPLAY_PRIMS);
assert!(l.truncated && points(&l) > 0 && points(&l) <= 220, "{space:?}: {}", points(&l));
assert!(full.prims.iter().any(|p| p.kind == Kind::Point) && l.prims.iter().all(|p| p.kind != Kind::Point), "{space:?}");
// Pieces that fill the list exactly leave no room for the last point.
for l in [build(MAX_DISPLAY_POINTS, full.prims.len() - 1), build(points(&full) - 1, MAX_DISPLAY_PRIMS)] {
assert!(l.truncated && l.prims.len() == full.prims.len() - 1, "{space:?}: {} of {}", l.prims.len(), full.prims.len());
}
}
}
/// The zigzag drawn 0.2 wide: one primitive of triangles, seen through a viewport whose model
/// window starts at y = 1, and a point after it on the layout.
fn wide_zigzag_through_viewport() -> Drawing {
let mut d = Drawing::new_imperial();
let EntityKind::LwPolyline(mut wide) = zigzag() else { panic!("a polyline") };
wide.const_width = 0.2;
d.add(&Space::Model, Common::default(), EntityKind::LwPolyline(wide)).unwrap();
let paper = Space::Paper("Layout1".into());
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap();
d.add(&paper, Common::default(), point_at(5.0)).unwrap();
d
}
#[test]
fn fills_cut_by_a_clip_stop_at_the_list_limits_and_say_so() {
// Each triangle the window's edge crosses becomes a fan with more points. With room for part
// of the clipped fill, the triangles that fit are drawn up to the limit, the rest is not built,
// and the list says it was left out; the point after the viewport is not drawn either.
let d = wide_zigzag_through_viewport();
let paper = Space::Paper("Layout1".into());
let build =
|max_points| crate::pipeline::build_space_within(&d, &paper, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
let full = build(MAX_DISPLAY_POINTS);
let fills = full.prims.iter().filter(|p| p.kind == Kind::Tris).count();
// The build charges the fill's points before it is clipped: fewer than the clip makes.
let charged =
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
assert!(
!full.truncated && fills == 1 && full.tris.len() > charged.tris.len() + 100,
"{fills} fills, {} of {}",
full.tris.len(),
charged.tris.len()
);
// Limits the charge passes and the clipped fill does not fit.
for limit in [points(&full) - (full.tris.len() - charged.tris.len()) / 2, full.verts.len() + charged.tris.len()] {
let l = build(limit);
assert!(l.truncated && !l.tris.is_empty() && full.tris.starts_with(&l.tris), "{limit}: {}", l.tris.len());
// Whole triangles, up to the limit.
assert!(l.tris.len() % 3 == 0 && points(&l) <= limit && points(&l) + 3 > limit, "{limit}: {}", points(&l));
assert!(l.prims.iter().all(|p| p.kind != Kind::Point), "{limit}");
}
// Clipped into a list of its own (as a preview's clipped copy is, with no build to stop), the
// cut fill marks that list truncated too.
let mut list = DisplayList::default();
let window = crate::viewports::Clip::Rect(Bounds2::new(Vec2::new(1.0, 1.0), Vec2::new(9.0, 9.0)));
let fits = crate::viewports::append_clipped(&mut list, &charged, &window, crate::viewports::Limits { points: 300, prims: 10 });
assert!(!fits && list.truncated && list.tris.len() == 300, "{}", list.tris.len());
}
#[test]
fn a_clipped_preview_keeps_what_its_list_left_out() {
// A point, then a zigzag the point budget leaves out: the list says so, and so does its copy
// clipped to a viewport's outline (the preview of a command inside a clipped viewport).
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), point_at(5.0)).unwrap();
d.add(&Space::Model, Common::default(), zigzag()).unwrap();
let mut l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 100, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
assert!(l.truncated && l.prims.len() == 1, "{} prims", l.prims.len());
(l.undashed, l.expanded) = (2, 3);
let square = [Vec2::new(-100.0, -100.0), Vec2::new(100.0, -100.0), Vec2::new(100.0, 100.0), Vec2::new(-100.0, 100.0)];
let c = crate::clip_list(&l, &crate::clip::PolyClip::new(&square).unwrap());
assert_eq!(c.prims.len(), 1);
assert!(c.truncated);
assert_eq!((c.undashed, c.expanded), (2, 3));
}
#[test]
fn layout_plot_style_outlines_stop_at_the_list_limits_and_say_so() {
// A plot style's line ends turn each wide line into a filled outline after the build, outside
// its budgets (#1603). Drawn on a layout or inside one of its viewports, the outlines stop at
// the build's point limit: every line is still drawn, those past it as plain lines.
let round = cadcraft_doc::PlotStyleTable::color_dependent("round.ctb", "", |i| {
(i == 1).then(|| cadcraft_doc::PlotStyle { lineweight: Some(100), end: cadcraft_doc::EndStyle::Round, ..Default::default() })
});
let opts = Options { plot_style_table: Some(std::sync::Arc::new(round)), lineweights: true, ..Default::default() };
let paper = Space::Paper("Layout1".into());
for space in [paper.clone(), Space::Model] {
let mut d = Drawing::new_metric();
for k in 0..20 {
let y = 10.0 + 4.0 * f64::from(k);
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(10.0, y, 0.0), b: Vec3::new(90.0, y, 0.0) });
d.add(&space, Common { color: Color::Index(1), ..Default::default() }, line).unwrap();
}
if space == Space::Model {
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(50.0, 50.0), 100.0, 100.0, Vec2::new(50.0, 50.0), 100.0, 2))).unwrap();
}
let build = |max_points| crate::pipeline::build_space_within(&d, &paper, &opts, false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
let full = build(MAX_DISPLAY_POINTS);
let outlines = full.prims.iter().filter(|p| p.kind == Kind::Tris).count();
assert!(!full.truncated && outlines == 20, "{space:?}: {outlines} outlines");
let limit = points(&full) / 2;
let l = build(limit);
let plain = l.prims.iter().filter(|p| p.kind == Kind::Polyline).count();
assert!(l.truncated && points(&l) <= limit, "{space:?}: {} of {limit}", points(&l));
assert!(l.prims.len() == full.prims.len() && plain > 0 && plain < 20, "{space:?}: {plain} plain of {}", l.prims.len());
}
}
#[test]
fn viewport_outlines_stop_at_the_room_the_layout_has_left() {
// Viewport contents get their plot style outlines before they are clipped into the layout's
// list, which already holds the objects drawn before the viewport. Outlines made within the
// build's whole limit could fit the contents' own list but not the layout's: the append then
// stopped part-way and spent the build, so the last line in the viewport and the layout
// objects after it were left out, though their plain lines fit. Within the room the layout's
// list has left, every object is drawn and only outlines are left out.
let round = cadcraft_doc::PlotStyleTable::color_dependent("round.ctb", "", |i| {
(i == 1).then(|| cadcraft_doc::PlotStyle { lineweight: Some(100), end: cadcraft_doc::EndStyle::Round, ..Default::default() })
});
let opts = Options { plot_style_table: Some(std::sync::Arc::new(round)), lineweights: true, ..Default::default() };
let paper = Space::Paper("Layout1".into());
let line = |y: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(10.0, y, 0.0), b: Vec3::new(90.0, y, 0.0) });
let plain = || Common { color: Color::Index(2), ..Default::default() };
let mut d = Drawing::new_metric();
// Before the viewport: 40 plain lines and 10 solids on the layout.
for k in 0..40 {
d.add(&paper, plain(), line(150.0 + f64::from(k))).unwrap();
}
for k in 0..10 {
let x = 120.0 + 5.0 * f64::from(k);
let corners = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 4.0, 0.0, 0.0), Vec3::new(x, 4.0, 0.0), Vec3::new(x + 4.0, 4.0, 0.0)];
d.add(&paper, plain(), EntityKind::Solid(cadcraft_doc::Solid { corners })).unwrap();
}
// 20 round-ended lines seen through the viewport, and 5 plain lines on the layout after it.
for k in 0..20 {
d.add(&Space::Model, Common { color: Color::Index(1), ..Default::default() }, line(10.0 + 4.0 * f64::from(k))).unwrap();
}
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(50.0, 50.0), 100.0, 100.0, Vec2::new(50.0, 50.0), 100.0, 2))).unwrap();
let after = [200.0, 201.0, 202.0, 203.0, 204.0];
for y in after {
d.add(&paper, plain(), line(y)).unwrap();
}
let build = |max_points| crate::pipeline::build_space_within(&d, &paper, &opts, false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
let plain_lines = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Polyline).count();
let full = build(MAX_DISPLAY_POINTS);
assert!(!full.truncated && full.prims.iter().filter(|p| p.kind == Kind::Tris).count() == 30);
// Room for every object but the last outline. The contents' own list (their plain lines'
// vertices and every outline) fits that limit; after the objects before the viewport it
// doesn't.
let tail: usize = full.prims.iter().rev().take(after.len()).map(|p| full.points(p).len()).sum();
let limit = points(&full) - tail - 1;
let l = build(limit);
assert!(l.truncated && points(&l) <= limit, "{} of {limit}", points(&l));
assert_eq!(l.prims.len(), full.prims.len(), "every object is drawn");
assert!(plain_lines(&l) > plain_lines(&full), "some lines in the viewport keep their plain line");
}
/// A block reference clipped (XCLIP, frame off) to a large rectangle, of block "Z" holding `kind`.
fn xclipped_ref(d: &mut Drawing, kind: EntityKind, at: Vec3) -> EntityKind {
if d.block("Z").is_none() {
let mut blk = cadcraft_doc::Block::new("Z");
blk.entities.push(block_entity(1, Common::default(), kind));
d.blocks.insert("Z".into(), std::sync::Arc::new(blk));
}
let EntityKind::Insert(mut ins) = insert_of("Z") else { panic!("an insert") };
ins.insert = at;
ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(-100.0, 1.0), Vec2::new(100.0, 100.0)]));
EntityKind::Insert(ins)
}
#[test]
fn attributes_cut_by_a_clip_say_what_the_budget_left_out() {
// The last object of the drawing: a clipped reference whose attribute text runs out of points.
let mut d = Drawing::new_imperial();
d.header.set_i64("XCLIPFRAME", 0);
let kind = xclipped_ref(&mut d, line_common(Common::default()).1, Vec3::ZERO);
let EntityKind::Insert(mut ins) = kind else { panic!("an insert") };
let mut a = attrib("TAG");
a.text.insert = Vec3::new(1.0, 2.0, 0.0);
a.text.value = "ABCDEFGHIJKLMNOP".into();
ins.attribs.push(a);
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let build = |max_points| {
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS)
};
let full = build(MAX_DISPLAY_POINTS);
assert!(!full.truncated && points(&full) > 20, "{}", points(&full));
let l = build(points(&full) - 1);
assert!(l.truncated && points(&l) < points(&full), "{} of {}", points(&l), points(&full));
}
#[test]
fn parts_built_on_all_cores_are_joined_within_the_list_limits() {
// Two clipped zigzags in different parts of the parallel build: each part fits the list's
// limits and the build's counts, which hold the zigzags and not their pieces; together they
// don't fit.
let mut d = Drawing::new_imperial();
d.header.set_i64("XCLIPFRAME", 0);
for i in 0..600 {
let kind = if i == 0 || i == 300 { xclipped_ref(&mut d, zigzag(), Vec3::ZERO) } else { point_at(f64::from(i)) };
d.add(&Space::Model, Common::default(), kind).unwrap();
}
let build = |max_points, max_prims| {
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, max_points, max_prims, MAX_DASH_ELEMENTS)
};
let full = build(MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS);
assert!(!full.truncated && full.prims.len() > 700 && points(&full) > 1000, "{} prims, {} points", full.prims.len(), points(&full));
let max = full.prims.len() - 50;
let l = build(MAX_DISPLAY_POINTS, max);
assert!(l.truncated && l.prims.len() <= max, "{} of {max}", l.prims.len());
let max = points(&full) - 50;
let l = build(max, MAX_DISPLAY_PRIMS);
assert!(l.truncated && points(&l) <= max, "{} of {max}", points(&l));
// Exactly as much as the parts hold is joined whole.
for l in [build(MAX_DISPLAY_POINTS, full.prims.len()), build(points(&full), MAX_DISPLAY_PRIMS)] {
assert!(!l.truncated && l.prims.len() == full.prims.len(), "{} of {}", l.prims.len(), full.prims.len());
}
}
// ---------- dash budget (#1069, #1923) ---------- // ---------- dash budget (#1069, #1923) ----------
/// A drawing of lines on DASHED (0.5, -0.25), one per entry of `periods` and that many periods /// A drawing of lines on DASHED (0.5, -0.25), one per entry of `periods` and that many periods
@@ -2145,12 +1619,11 @@ fn a_run_past_its_dash_limit_is_drawn_continuous_and_says_so() {
#[test] #[test]
fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() { fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() {
let d = dashed_lines(&[1000.0; 40]); let d = dashed_lines(&[1000.0; 40]);
let full = let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS);
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
assert!(!full.truncated && full.undashed == 0); assert!(!full.truncated && full.undashed == 0);
let each = prims_per_entity(&full); let each = prims_per_entity(&full);
assert!(each.len() == 40 && each.iter().all(|n| *n > 1000), "{each:?}"); assert!(each.len() == 40 && each.iter().all(|n| *n > 1000), "{each:?}");
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 40_000); let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, 40_000);
let dashed = 40 - l.undashed; let dashed = 40 - l.undashed;
assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed); assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed);
assert!(dashed * 2004 <= 40_000, "{dashed} lines dashed"); assert!(dashed * 2004 <= 40_000, "{dashed} lines dashed");
@@ -2165,7 +1638,7 @@ fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() {
fn dashed_runs_built_on_all_cores_share_the_dash_budget() { fn dashed_runs_built_on_all_cores_share_the_dash_budget() {
// 600 lines of 100 periods (204 elements each): enough for the parallel build. // 600 lines of 100 periods (204 elements each): enough for the parallel build.
let d = dashed_lines(&[100.0; 600]); let d = dashed_lines(&[100.0; 600]);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 20_000); let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, 20_000);
let dashed = 600 - l.undashed; let dashed = 600 - l.undashed;
assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed); assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed);
assert!(dashed * 204 <= 20_000, "{dashed} lines dashed"); assert!(dashed * 204 <= 20_000, "{dashed} lines dashed");
@@ -2189,56 +1662,10 @@ fn runs_seen_through_a_viewport_are_counted_and_spend_the_layout_dash_budget() {
let l = build_plot(&d, &paper, &Options::default()); let l = build_plot(&d, &paper, &Options::default());
assert!(l.prims.iter().any(|p| p.handle == VIEWPORT_CONTENT), "the lines show in the viewport"); assert!(l.prims.iter().any(|p| p.handle == VIEWPORT_CONTENT), "the lines show in the viewport");
assert!(l.truncated && l.undashed == 1, "{}", l.undashed); assert!(l.truncated && l.undashed == 1, "{}", l.undashed);
let l = crate::pipeline::build_space_within(&d, &paper, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 100); let l = crate::pipeline::build_space_within(&d, &paper, &Options::default(), true, MAX_DISPLAY_POINTS, 100);
assert_eq!(l.undashed, 2); assert_eq!(l.undashed, 2);
} }
/// Viewports after a spent layout build draw nothing, and the list says what they leave out: also
/// when the build was spent by a list filled exactly, before anything was left out. A list that
/// left out only dashes still draws them.
#[test]
fn viewports_after_a_spent_layout_build_say_what_they_leave_out() {
// A point seen through a rectangular viewport and then through a clipped one (which has no
// border), on a layout with a dashed line and the clip outline first: nothing on the layout
// after the viewports marks the list.
let paper = Space::Paper("Layout1".into());
let layout = |second_on: bool| {
let mut d = dashed_lines(&[]);
let point = EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 });
d.add(&Space::Model, Common::default(), point).unwrap();
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 12.0, 0.0), b: Vec3::new(750.0, 12.0, 0.0) });
d.add(&paper, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap();
let vertices = [(20.0, 0.0), (30.0, 0.0), (30.0, 10.0), (20.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
let square = cadcraft_doc::LwPolyline { vertices, closed: true, const_width: 0.0, elevation: 0.0, plinegen: false };
let outline = d.add(&paper, Common::default(), EntityKind::LwPolyline(square)).unwrap();
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 5.0), 10.0, 10.0, Vec2::new(5.0, 5.0), 10.0, 2))).unwrap();
let mut clipped = vp(Vec2::new(25.0, 5.0), 10.0, 10.0, Vec2::new(5.0, 5.0), 10.0, 3);
clipped.clip = Some(outline);
clipped.on = second_on;
d.add(&paper, Common::default(), EntityKind::Viewport(clipped)).unwrap();
d
};
let build = |d: &Drawing, max_points, max_dashes| {
crate::pipeline::build_space_within(d, &paper, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, max_dashes)
};
let shown = |l: &DisplayList| l.prims.iter().filter(|p| p.handle == VIEWPORT_CONTENT).count();
let (both, first) = (layout(true), layout(false));
let full = build(&both, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS);
assert!(!full.truncated && shown(&full) == 2, "{}", shown(&full));
// The layout up to the first viewport's point fills the list exactly: whole when the second
// viewport is off, and its point said to be left out when it is on.
let exact = points(&build(&first, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS));
let l = build(&first, exact, MAX_DASH_ELEMENTS);
assert!(!l.truncated && shown(&l) == 1, "{}", shown(&l));
let l = build(&both, exact, MAX_DASH_ELEMENTS);
assert!(l.truncated && shown(&l) == 1, "{}", shown(&l));
let l = build(&both, exact - 1, MAX_DASH_ELEMENTS);
assert!(l.truncated && shown(&l) == 0, "{}", shown(&l));
// The dashed line past the dash budget: drawn continuous, and both viewports drawn.
let l = build(&both, MAX_DISPLAY_POINTS, 100);
assert!(l.truncated && l.undashed == 1 && shown(&l) == 2, "{} {}", l.undashed, shown(&l));
}
/// A block reference cut by an XCLIP boundary is drawn apart and then joined: a run in it drawn /// A block reference cut by an XCLIP boundary is drawn apart and then joined: a run in it drawn
/// continuous is still counted. /// continuous is still counted.
#[test] #[test]
@@ -2269,7 +1696,7 @@ fn linetype_text_is_left_off_a_run_past_the_dash_budget() {
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(95.0, y, 0.0) }); let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(95.0, y, 0.0) });
d.add(&Space::Model, Common { linetype: "GAS".into(), ..Default::default() }, line).unwrap(); d.add(&Space::Model, Common { linetype: "GAS".into(), ..Default::default() }, line).unwrap();
} }
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 400); let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, 400);
let each = prims_per_entity(&l); let each = prims_per_entity(&l);
assert!(matches!(each.as_slice(), [first, 1] if *first > 101), "{each:?}"); assert!(matches!(each.as_slice(), [first, 1] if *first > 101), "{each:?}");
assert_eq!(l.undashed, 1); assert_eq!(l.undashed, 1);
+102 -157
View File
@@ -1,11 +1,13 @@
#[cfg(not(target_arch = "wasm32"))]
use super::display::append;
use super::display::{DImage, DPrim, DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::display::{DImage, DPrim, DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT};
use super::draw::entity; use super::draw::entity;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use super::pipeline::PARALLEL_CHUNK; use super::pipeline::PARALLEL_CHUNK;
use super::pipeline::{Options, style_table, top_ctx, with_point_view}; use super::pipeline::{Options, style_table, top_ctx, with_point_view};
use super::{ use super::{
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Fade, Handle, MAX_BLOCK_EXPANSION, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2,
Mat3, Pen, Space, Vec2, clip, paper, pen, plotstyle, clip, paper, pen, plotstyle,
}; };
/// Upper bound on viewports drawn per layout (hostile files). /// Upper bound on viewports drawn per layout (hostile files).
@@ -68,10 +70,8 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
} }
let opts = &with_point_view(d, space, opts); let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t)); let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t));
let (points, prims, dashes) = let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
(std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let loops = std::sync::OnceLock::new(); let loops = std::sync::OnceLock::new();
let fade = Fade::of(d);
let mut b = Builder { let mut b = Builder {
list: DisplayList::default(), list: DisplayList::default(),
opts, opts,
@@ -82,12 +82,9 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
transparency: 0, transparency: 0,
points: &points, points: &points,
max_points: MAX_DISPLAY_POINTS, max_points: MAX_DISPLAY_POINTS,
prims: &prims,
max_prims: MAX_DISPLAY_PRIMS,
dashes: &dashes, dashes: &dashes,
max_dashes: MAX_DASH_ELEMENTS, max_dashes: MAX_DASH_ELEMENTS,
loops: &loops, loops: &loops,
fade: fade.as_ref(),
}; };
contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle)); contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle));
b.list b.list
@@ -99,12 +96,6 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
if b.list.expanded >= MAX_BLOCK_EXPANSION || !vp.on { if b.list.expanded >= MAX_BLOCK_EXPANSION || !vp.on {
return; return;
} }
// A spent build draws nothing more: once its list says so, the model is not scanned (and its
// objects' bounds worked out) for nothing. A build spent by a list filled exactly has left
// nothing out yet: the scan still marks the list for the contents it can't draw.
if b.spent() && b.list.truncated {
return;
}
let center = vp.center.xy(); let center = vp.center.xy();
let ok = |v: f64| v.is_finite() && v > 0.0; let ok = |v: f64| v.is_finite() && v > 0.0;
if !(ok(vp.width) && ok(vp.height) && ok(vp.view_height) && center.is_finite() && vp.view_center.is_finite()) { if !(ok(vp.width) && ok(vp.height) && ok(vp.view_height) && center.is_finite() && vp.view_center.is_finite()) {
@@ -148,12 +139,9 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0, transparency: 0,
points: b.points, points: b.points,
max_points: b.max_points, max_points: b.max_points,
prims: b.prims,
max_prims: b.max_prims,
dashes: b.dashes, dashes: b.dashes,
max_dashes: b.max_dashes, max_dashes: b.max_dashes,
loops: b.loops, loops: b.loops,
fade: b.fade,
}; };
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK; let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK;
@@ -165,8 +153,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. // As `build_parallel`: chunks built side by side, joined in drawing order.
use rayon::prelude::*; use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = d.model.iter().collect(); let ents: Vec<&std::sync::Arc<Entity>> = d.model.iter().collect();
let (opts, points, max_points, prims, max_prims, dashes, max_dashes, loops, fade) = let (opts, points, max_points, dashes, max_dashes, loops) = (b.opts, b.points, b.max_points, b.dashes, b.max_dashes, b.loops);
(b.opts, b.points, b.max_points, b.prims, b.max_prims, b.dashes, b.max_dashes, b.loops, b.fade);
let parts: Vec<DisplayList> = ents let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK) .par_chunks(PARALLEL_CHUNK)
.map(|chunk| { .map(|chunk| {
@@ -180,12 +167,9 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0, transparency: 0,
points, points,
max_points, max_points,
prims,
max_prims,
dashes, dashes,
max_dashes, max_dashes,
loops, loops,
fade,
}; };
let c = ctx(); let c = ctx();
for me in chunk.iter().filter(|me| seen(me)) { for me in chunk.iter().filter(|me| seen(me)) {
@@ -194,7 +178,9 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
part.list part.list
}) })
.collect(); .collect();
sub.join(parts); for part in parts {
append(&mut sub.list, part);
}
} }
} else { } else {
let c = ctx(); let c = ctx();
@@ -213,19 +199,12 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
b.list.texts.push(PlotText { prim: PlotText::NONE, ..t }); b.list.texts.push(PlotText { prim: PlotText::NONE, ..t });
} }
} }
// The contents are in paper units now: draw their pens before clipping, within the room the // The contents are in paper units now: draw their pens before clipping.
// layout's list has left rather than the build's whole limit. Outlines that fit the contents' pen::apply(&mut sub.list, unit_mm);
// own list but not the layout's would stop the append part-way and spend the build, leaving
// out contents and layout objects whose plain lines fit.
let limits = b.limits();
let room = limits.points.saturating_sub(b.list.verts.len().saturating_add(b.list.tris.len()));
pen::apply_within(&mut sub.list, unit_mm, room);
b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded); b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded);
b.list.truncated |= sub.list.truncated; b.list.truncated |= sub.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(sub.list.undashed); b.list.undashed = b.list.undashed.saturating_add(sub.list.undashed);
if !append_clipped(&mut b.list, &sub.list, clip, limits) { append_clipped(&mut b.list, &sub.list, clip);
b.spend();
}
} }
/// The clip region of a clipped viewport: the outline of its clip boundary entity, when that /// The clip region of a clipped viewport: the outline of its clip boundary entity, when that
@@ -238,54 +217,13 @@ pub fn viewport_clip(d: &Drawing, handle: Handle, vp: &cadcraft_doc::Viewport) -
} }
/// `list` clipped to `clip` (a clipped viewport's outline in the list's own units), for a list /// `list` clipped to `clip` (a clipped viewport's outline in the list's own units), for a list
/// drawn inside a clipped viewport apart from its contents. It says what `list` left out /// drawn inside a clipped viewport apart from its contents.
/// (`truncated`, `undashed`) and counts its block copies, as viewport contents do.
pub fn clip_list(list: &DisplayList, clip: &clip::PolyClip) -> DisplayList { pub fn clip_list(list: &DisplayList, clip: &clip::PolyClip) -> DisplayList {
let mut out = DisplayList { truncated: list.truncated, undashed: list.undashed, expanded: list.expanded, ..DisplayList::default() }; let mut out = DisplayList::default();
append_clipped(&mut out, list, &Clip::Poly(clip), Limits::BUILD); append_clipped(&mut out, list, &Clip::Poly(clip));
out out
} }
/// What one display list may hold. Clipping can cut one primitive into many pieces, each with
/// points of its own where it crosses the clip, and the build's budgets count the primitive, not
/// its pieces: the pieces appended to a list stop at these limits, which mark it truncated, and
/// what the build draws into a list afterwards checks them too.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Limits {
pub points: usize,
pub prims: usize,
}
impl Limits {
/// A build's own limits: [`MAX_DISPLAY_POINTS`] and [`MAX_DISPLAY_PRIMS`].
const BUILD: Limits = Limits { points: MAX_DISPLAY_POINTS, prims: MAX_DISPLAY_PRIMS };
/// Whether `list` has room for one more primitive of `n` points; when it has none, the list
/// is marked truncated.
pub(crate) fn room(self, list: &mut DisplayList, n: usize) -> bool {
let ok = list.prims.len() < self.prims && list.verts.len().saturating_add(list.tris.len()).saturating_add(n) <= self.points;
if !ok {
list.truncated = true;
}
ok
}
/// The room `list` has left: what a clip appending to it may produce.
fn left(self, list: &DisplayList) -> clip::Cap {
let pieces = self.prims.saturating_sub(list.prims.len());
let points = if pieces == 0 { 0 } else { self.points.saturating_sub(list.verts.len().saturating_add(list.tris.len())) };
clip::Cap { points, pieces }
}
}
/// `whole`, marking `list` truncated when it is false (a clip stopped at the room `list` had).
fn whole(list: &mut DisplayList, whole: bool) -> bool {
if !whole {
list.truncated = true;
}
whole
}
/// What viewport contents are clipped to. /// What viewport contents are clipped to.
pub(crate) enum Clip<'a> { pub(crate) enum Clip<'a> {
/// The viewport rectangle (the fast path). /// The viewport rectangle (the fast path).
@@ -296,21 +234,21 @@ pub(crate) enum Clip<'a> {
Outside(&'a clip::PolyClip), Outside(&'a clip::PolyClip),
} }
/// Append `src` to `dst`, clipped to `clip`, within `limits`; false once a piece did not fit /// Append `src` to `dst`, clipped to `clip`.
/// (`dst` is then marked truncated and nothing after that piece is appended). pub(crate) fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) {
pub(crate) fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip, limits: Limits) -> bool { for p in &src.prims {
src.prims.iter().all(|p| clip_prim(dst, src, p, clip, limits)) clip_prim(dst, src, p, clip);
}
} }
/// Append `src` to `dst` clipped to `clip` within `limits`, keeping each primitive's plot style /// Append `src` to `dst` clipped to `clip`, keeping each primitive's plot style pen and, for a
/// pen and, for a glyph that the clip leaves whole, its plotted text (an XCLIP-clipped block /// glyph that the clip leaves whole, its plotted text (an XCLIP-clipped block reference).
/// reference); false once a piece did not fit, as [`append_clipped`]. pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) {
pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip: &Clip, limits: Limits) -> bool {
let texts: std::collections::HashMap<usize, &PlotText> = let texts: std::collections::HashMap<usize, &PlotText> =
src.texts.iter().filter(|t| t.prim != PlotText::NONE && t.prim != PlotText::CLIPPED).map(|t| (t.prim as usize, t)).collect(); src.texts.iter().filter(|t| t.prim != PlotText::NONE && t.prim != PlotText::CLIPPED).map(|t| (t.prim as usize, t)).collect();
for (i, p) in src.prims.iter().enumerate() { for (i, p) in src.prims.iter().enumerate() {
let first = dst.prims.len(); let first = dst.prims.len();
let fits = clip_prim(dst, src, p, clip, limits); clip_prim(dst, src, p, clip);
// Each piece keeps its source's layer (block contents not on layer 0 keep theirs). // Each piece keeps its source's layer (block contents not on layer 0 keep theirs).
if let Some(layer) = src.prim_layers.get(i).copied() { if let Some(layer) = src.prim_layers.get(i).copied() {
for k in first..dst.prims.len() { for k in first..dst.prims.len() {
@@ -332,114 +270,122 @@ pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip
{ {
dst.texts.push(PlotText { prim, ..(**t).clone() }); dst.texts.push(PlotText { prim, ..(**t).clone() });
} }
if !fits {
return false;
}
} }
true
} }
/// Append primitive `p` of `src` to `dst`, clipped to `clip`, within `limits`; false when a piece /// Append primitive `p` of `src` to `dst`, clipped to `clip`.
/// did not fit (the pieces after it are not appended). fn clip_prim(dst: &mut DisplayList, src: &DisplayList, p: &DPrim, clip: &Clip) {
/// {
/// Lines and fills are clipped within the room `dst` has left, since a clip can make far more let pts = src.points(p);
/// points than `p` has: the pieces, or the triangles, that fit are appended and the rest is left match (p.kind, clip) {
/// out, without building it first. (Kind::Polyline, Clip::Rect(rect)) => {
fn clip_prim(dst: &mut DisplayList, src: &DisplayList, p: &DPrim, clip: &Clip, limits: Limits) -> bool { for piece in clip::clip_polyline(pts, rect) {
let pts = src.points(p); push_raw(dst, p, Kind::Polyline, &piece);
let cap = limits.left(dst); }
let pieces = |dst: &mut DisplayList, (cut, all): (Vec<Vec<Vec2>>, bool)| {
cut.iter().all(|piece| push_raw(dst, p, Kind::Polyline, piece, limits)) && whole(dst, all)
};
let fill = |dst: &mut DisplayList, (cut, all): (Vec<Vec2>, bool)| push_raw(dst, p, p.kind, &cut, limits) && whole(dst, all);
match (p.kind, clip) {
(Kind::Polyline, Clip::Rect(rect)) => pieces(dst, clip::clip_polyline_within(pts, rect, cap)),
(Kind::Polyline, Clip::Poly(c)) => pieces(dst, c.clip_polyline_within(pts, cap)),
(Kind::Polyline, Clip::Outside(c)) => pieces(dst, c.clip_polyline_outside_within(pts, cap)),
(Kind::Tris | Kind::Mask, Clip::Rect(rect)) => fill(dst, clip::clip_triangles_within(pts, rect, cap.points)),
(Kind::Tris | Kind::Mask, Clip::Poly(c)) => fill(dst, c.clip_triangles_within(pts, cap.points)),
(Kind::Tris | Kind::Mask, Clip::Outside(c)) => fill(dst, c.clip_triangles_outside_within(pts, cap.points)),
(Kind::Point, _) => {
let inside = |q: Vec2| match clip {
Clip::Rect(rect) => rect.contains(q),
Clip::Poly(c) => c.contains(q),
Clip::Outside(c) => !c.contains(q),
};
match pts.first() {
Some(q) if inside(*q) => push_raw(dst, p, Kind::Point, &[*q], limits),
_ => true,
} }
} (Kind::Polyline, Clip::Poly(c)) => {
(Kind::Image { index }, _) => match src.images.get(index as usize) { for piece in c.clip_polyline(pts) {
Some(img) => push_clipped_image(dst, p, img, pts, clip, limits), push_raw(dst, p, Kind::Polyline, &piece);
None => true, }
}, }
(Kind::Infinite { ray }, _) => { (Kind::Polyline, Clip::Outside(c)) => {
let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) else { return true }; for piece in c.clip_polyline_outside(pts) {
match clip { push_raw(dst, p, Kind::Polyline, &piece);
Clip::Rect(rect) => match clip::clip_infinite(*base, *dir, ray, rect) { }
Some((a, c)) => push_raw(dst, p, Kind::Polyline, &[a, c], limits), }
None => true, (Kind::Tris | Kind::Mask, Clip::Rect(rect)) => {
}, let t = clip::clip_triangles(pts, rect);
// A line or ray has two points: its pieces are at most one per outline edge. push_raw(dst, p, p.kind, &t);
Clip::Poly(c) => pieces(dst, (c.clip_infinite(*base, *dir, ray), true)), }
Clip::Outside(c) => pieces(dst, (c.clip_infinite_outside(*base, *dir, ray), true)), (Kind::Tris | Kind::Mask, Clip::Poly(c)) => {
let t = c.clip_triangles(pts);
push_raw(dst, p, p.kind, &t);
}
(Kind::Tris | Kind::Mask, Clip::Outside(c)) => {
let t = c.clip_triangles_outside(pts);
push_raw(dst, p, p.kind, &t);
}
(Kind::Point, _) => {
let inside = |q: Vec2| match clip {
Clip::Rect(rect) => rect.contains(q),
Clip::Poly(c) => c.contains(q),
Clip::Outside(c) => !c.contains(q),
};
if let Some(q) = pts.first()
&& inside(*q)
{
push_raw(dst, p, Kind::Point, &[*q]);
}
}
(Kind::Image { index }, _) => {
if let Some(img) = src.images.get(index as usize) {
push_clipped_image(dst, p, img, pts, clip);
}
}
(Kind::Infinite { ray }, Clip::Rect(rect)) => {
if let (Some(base), Some(dir)) = (pts.first(), pts.get(1))
&& let Some((a, c)) = clip::clip_infinite(*base, *dir, ray, rect)
{
push_raw(dst, p, Kind::Polyline, &[a, c]);
}
}
(Kind::Infinite { ray }, Clip::Poly(c)) => {
if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) {
for piece in c.clip_infinite(*base, *dir, ray) {
push_raw(dst, p, Kind::Polyline, &piece);
}
}
}
(Kind::Infinite { ray }, Clip::Outside(c)) => {
if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) {
for piece in c.clip_infinite_outside(*base, *dir, ray) {
push_raw(dst, p, Kind::Polyline, &piece);
}
}
} }
} }
} }
} }
/// Append image `img` (primitive `p`, corners `corners`) to `dst`, to be cut to `clip` when it /// Append image `img` (primitive `p`, corners `corners`) to `dst`, to be cut to `clip` when it
/// is drawn: the picture is not cut here, the outline is added to those it carries. False when /// is drawn: the picture is not cut here, the outline is added to those it carries.
/// it did not fit. fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: &[Vec2], clip: &Clip) {
fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: &[Vec2], clip: &Clip, limits: Limits) -> bool {
let (outline, area) = match clip { let (outline, area) = match clip {
Clip::Rect(rect) => (vec![rect.min, Vec2::new(rect.max.x, rect.min.y), rect.max, Vec2::new(rect.min.x, rect.max.y)], *rect), Clip::Rect(rect) => (vec![rect.min, Vec2::new(rect.max.x, rect.min.y), rect.max, Vec2::new(rect.min.x, rect.max.y)], *rect),
Clip::Poly(c) => (c.polygon().to_vec(), c.bounds()), Clip::Poly(c) => (c.polygon().to_vec(), c.bounds()),
// An image can only be cut to the inside of an outline: under an inverted XCLIP it is // An image can only be cut to the inside of an outline: under an inverted XCLIP it is
// drawn whole, which shows too much rather than losing any of it. // drawn whole, which shows too much rather than losing any of it.
Clip::Outside(_) => { Clip::Outside(_) => {
let Ok(index) = u32::try_from(dst.images.len()) else { return true }; let Ok(index) = u32::try_from(dst.images.len()) else { return };
if !limits.room(dst, corners.len()) {
return false;
}
dst.images.push(img.clone()); dst.images.push(img.clone());
return push_raw(dst, p, Kind::Image { index }, corners, limits); push_raw(dst, p, Kind::Image { index }, corners);
return;
} }
}; };
let own = Bounds2::from_points(corners.iter().copied()); let own = Bounds2::from_points(corners.iter().copied());
if !own.intersects(&area) { if !own.intersects(&area) {
return true; return;
} }
if !limits.room(dst, corners.len()) { let Ok(index) = u32::try_from(dst.images.len()) else { return };
return false;
}
let Ok(index) = u32::try_from(dst.images.len()) else { return true };
let mut img = img.clone(); let mut img = img.clone();
img.clips.push(outline); img.clips.push(outline);
dst.images.push(img); dst.images.push(img);
// The list's bounds take only the part inside the clip, as for the other primitives. // The list's bounds take only the part inside the clip, as for the other primitives.
let before = dst.bounds; let before = dst.bounds;
let fits = push_raw(dst, p, Kind::Image { index }, corners, limits); push_raw(dst, p, Kind::Image { index }, corners);
dst.bounds = before; dst.bounds = before;
dst.bounds.add(own.min.max(area.min)); dst.bounds.add(own.min.max(area.min));
dst.bounds.add(own.max.min(area.max)); dst.bounds.add(own.max.min(area.max));
fits
} }
/// Append one piece; false when `dst` has no room for it ([`Limits::room`]). A piece too short fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2]) {
/// to draw is left out and counts as appended.
fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2], limits: Limits) -> bool {
let min = match kind { let min = match kind {
Kind::Polyline => 2, Kind::Polyline => 2,
Kind::Tris | Kind::Mask => 3, Kind::Tris | Kind::Mask => 3,
_ => 1, _ => 1,
}; };
if pts.len() < min { if pts.len() < min {
return true; return;
}
if !limits.room(dst, pts.len()) {
return false;
} }
let tris = matches!(kind, Kind::Tris | Kind::Mask); let tris = matches!(kind, Kind::Tris | Kind::Mask);
let start = if tris { dst.tris.len() } else { dst.verts.len() } as u32; let start = if tris { dst.tris.len() } else { dst.verts.len() } as u32;
@@ -461,5 +407,4 @@ fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2], limits:
start, start,
len: pts.len() as u32, len: pts.len() as u32,
}); });
true
} }
-3
View File
@@ -1259,7 +1259,6 @@ fn paint_canvas(frame: CanvasPaint<'_>) {
app.canvas.draw_ms = crate::now_ms() - t0; app.canvas.draw_ms = crate::now_ms() - t0;
compare::paint(app, ui.ctx(), painter, &xf_paper, rect); compare::paint(app, ui.ctx(), painter, &xf_paper, rect);
blockedit::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). // Constraint bars and dynamic dimensional constraints (model space, or inside a viewport).
if sheet.is_none() || active_vp.is_some() { if sheet.is_none() || active_vp.is_some() {
let clip = match &active_vp { let clip = match &active_vp {
@@ -1367,5 +1366,3 @@ mod compare;
/// Background rebuilds of the display list for a new view. /// Background rebuilds of the display list for a new view.
mod images; mod images;
mod rebuild; mod rebuild;
/// The Edit Reference bar while a reference is edited in place (REFEDIT).
mod refedit;
+4 -2
View File
@@ -200,12 +200,14 @@ pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let s = &app.session.settings; let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 }; let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return }; let Ok(st) = app.session.state() else { return };
let space = st.edit_space();
let frozen = st.viewport_frozen();
let hit = match cycle { let hit = match cycle {
Some(i) => { Some(i) => {
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred); let cands = cadcraft_engine::pointmod::snap_candidates_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen);
cands.get(i % cands.len().max(1)).copied() cands.get(i % cands.len().max(1)).copied()
} }
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred), None => snap::osnap_with_frozen(&st.doc, &space, raw, ap, osmode, base, deferred, frozen),
}; };
let p = match (hit, app.canvas.snap) { let p = match (hit, app.canvas.snap) {
(Some(h), _) => { (Some(h), _) => {
-72
View File
@@ -1,72 +0,0 @@
//! 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 => {}
}
}
-31
View File
@@ -447,37 +447,6 @@ fn the_viewport_highlight_leaves_out_objects_the_viewport_does_not_draw() {
assert_eq!(outlined(&app, &mut highlight, both), both); assert_eq!(outlined(&app, &mut highlight, both), both);
} }
/// The highlight of a block reference inside the active viewport shows the parts that viewport
/// draws: not its part on a layer frozen there, which the other viewport's highlight shows.
#[test]
fn the_viewport_highlight_of_a_reference_leaves_out_the_parts_the_viewport_does_not_draw() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
for y in [0, 30] {
app.run("line", serde_json::json!({ "points": [[0, y], [100, y]] })).unwrap();
}
let lines = app.session.doc().unwrap().model.handles();
let (a, b) = viewports_freezing_hidden(&mut app);
// Inside a viewport the block's reference is made in model space, where the lines are.
app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap();
app.session.execute("properties.set", &serde_json::json!({ "handles": [lines[1].hex()], "layer": "Hidden" })).unwrap();
let parts: Vec<String> = lines.iter().map(|h| h.hex()).collect();
let made = app.session.execute("block", &serde_json::json!({ "name": "B", "base": [0, 0], "handles": parts })).unwrap();
let reference = Handle::parse_hex(made["insert"].as_str().unwrap()).unwrap();
assert_eq!(app.session.doc().unwrap().model.handles(), [reference], "the reference must be the one object in model space");
/// The heights at which `highlight` draws something for the reference.
fn heights(app: &CadApp, highlight: &mut VpHighlight, reference: Handle) -> Vec<f64> {
highlight.update(app.session.state().unwrap(), &[reference], 10.0);
let mut ys: Vec<f64> = highlight.list.prims.iter().map(|p| highlight.list.points(p)[0].y).collect();
ys.sort_by(f64::total_cmp);
ys
}
let mut highlight = VpHighlight::default();
app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap();
assert_eq!(heights(&app, &mut highlight, reference), [0.0, 30.0], "this viewport draws both parts");
app.session.execute("mspace", &serde_json::json!({ "handle": a })).unwrap();
assert_eq!(heights(&app, &mut highlight, reference), [0.0], "a part the viewport does not draw was highlighted");
}
/// Selection cycling's badge beside a resting pointer follows the layers frozen in the active /// Selection cycling's badge beside a resting pointer follows the layers frozen in the active
/// viewport: over two overlapping lines it shows while the viewport draws both, goes when the /// viewport: over two overlapping lines it shows while the viewport draws both, goes when the
/// layer of one of them is frozen there, and comes back when the layer is thawed. /// layer of one of them is frozen there, and comes back when the layer is thawed.
+4 -8
View File
@@ -274,10 +274,7 @@ pub(super) fn viewport_highlight_tolerance(scale: f64) -> f64 {
/// the hover are kept apart, so moving the cursor over objects doesn't tessellate the selection /// the hover are kept apart, so moving the cursor over objects doesn't tessellate the selection
/// again; each is rebuilt only when the drawing, the objects, the zoom band or the layers frozen /// again; each is rebuilt only when the drawing, the objects, the zoom band or the layers frozen
/// in the viewport change. An object on one of those layers is not drawn in the viewport, so it /// in the viewport change. An object on one of those layers is not drawn in the viewport, so it
/// is not highlighted there either, and neither are the parts of a block reference on them. The /// is not highlighted there either.
/// highlight is built as a selection through the viewport sees the objects, so a point on the
/// layer Defpoints in a block stays in it, as the definition points of a dimension are
/// ([`cadcraft_render::build_entities_in_viewport`]).
#[derive(Default)] #[derive(Default)]
pub(super) struct VpHighlight { pub(super) struct VpHighlight {
key: Option<u64>, key: Option<u64>,
@@ -289,19 +286,18 @@ pub(super) struct VpHighlight {
impl VpHighlight { impl VpHighlight {
pub(super) fn update(&mut self, st: &cadcraft_engine::DocState, handles: &[Handle], scale: f64) { pub(super) fn update(&mut self, st: &cadcraft_engine::DocState, handles: &[Handle], scale: f64) {
let tolerance = viewport_highlight_tolerance(scale); let tolerance = viewport_highlight_tolerance(scale);
// Entering another viewport changes what is drawn without changing the drawing.
let frozen = st.viewport_frozen();
let key = { let key = {
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new(); let mut h = std::collections::hash_map::DefaultHasher::new();
// Entering another viewport changes what is drawn without changing the drawing.
let frozen = st.viewport_frozen();
(st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles, frozen, super::list::font_generation()) (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles, frozen, super::list::font_generation())
.hash(&mut h); .hash(&mut h);
h.finish() h.finish()
}; };
if self.key != Some(key) { if self.key != Some(key) {
let ents = handles.iter().filter_map(|h| st.doc.model.get(*h)).filter(|e| !st.hidden_in_viewport(e)).map(|e| e.as_ref()); let ents = handles.iter().filter_map(|h| st.doc.model.get(*h)).filter(|e| !st.hidden_in_viewport(e)).map(|e| e.as_ref());
self.list = self.list = cadcraft_render::build_entities(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() });
cadcraft_render::build_entities_in_viewport(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() }, frozen);
self.key = Some(key); self.key = Some(key);
self.list_gen = self.list_gen.wrapping_add(1); self.list_gen = self.list_gen.wrapping_add(1);
} }
+2 -85
View File
@@ -379,10 +379,9 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
options_still_fit(app); options_still_fit(app);
for ev in events { for ev in events {
app.cmd.forget_stale_first(dyn_frame(app).is_some()); app.cmd.forget_stale_first(dyn_frame(app).is_some());
let space_is_text = app.session.space_is_text(&app.cmd.buffer);
// The options menu takes the arrows, Enter and Escape; typing closes it. // The options menu takes the arrows, Enter and Escape; typing closes it.
if app.cmd.options.is_some() { if app.cmd.options.is_some() {
let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !space_is_text; let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !text_prompt;
match &ev { match &ev {
_ if space => { _ if space => {
if let Some(k) = app.cmd.options.as_ref().and_then(|m| m.current()).map(str::to_owned) { if let Some(k) = app.cmd.options.as_ref().and_then(|m| m.current()).map(str::to_owned) {
@@ -413,7 +412,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
} }
match ev { match ev {
egui::Event::Text(t) => { egui::Event::Text(t) => {
if t == " " && !space_is_text { if t == " " && !text_prompt {
submit(app); submit(app);
} else { } else {
app.cmd.preedit.clear(); app.cmd.preedit.clear();
@@ -1357,85 +1356,3 @@ mod dyn_tab_tests {
assert!(!app.cmd.first_active()); assert!(!app.cmd.first_active());
} }
} }
#[cfg(test)]
mod lisp_space_tests {
use super::*;
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec2;
fn run_frame(app: &mut CadApp, ctx: &egui::Context, events: Vec<egui::Event>) {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),
events,
..Default::default()
};
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
});
out.textures_delta.clear();
}
#[test]
fn space_types_inside_an_open_lisp_expression_and_submits_once_closed() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let send = |app: &mut CadApp, text: &str| {
let mut events = Vec::new();
for c in text.chars() {
if c == ' ' {
events.push(egui::Event::Key {
key: egui::Key::Space,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
});
}
events.push(egui::Event::Text(c.to_string()));
}
run_frame(app, &ctx, events);
};
// Nested forms, an escaped quote, a `)` inside a string and a `;| ... |;` block comment
// stay open across spaces; once the outer `)` closes the form, Space evaluates it.
send(&mut app, "(defun c:greet () (princ \"hi \\\" ) there\") ;| ) |; (princ))");
assert_eq!(app.cmd.buffer, "(defun c:greet () (princ \"hi \\\" ) there\") ;| ) |; (princ))");
send(&mut app, " ");
assert!(app.cmd.buffer.is_empty());
send(&mut app, "greet ");
assert_eq!(app.session.log.last().map(String::as_str), Some("hi \" ) there"));
// At point and number prompts (including with the Dynamic Input options menu open),
// spaces stay inside `(...)` and Space after `)` answers the prompt.
send(&mut app, "(setq r 5) ");
send(&mut app, "circle ");
run_frame(
&mut app,
&ctx,
vec![egui::Event::Key { key: egui::Key::ArrowDown, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],
);
assert!(app.cmd.options.is_some());
send(&mut app, "(list 3 4) (* 2 r) ");
assert!(app.session.running.is_none());
let circle = app.session.doc().unwrap().model.iter().find_map(|e| match &e.kind {
EntityKind::Circle(c) => Some((c.center.xy(), c.radius)),
_ => None,
});
assert_eq!(circle, Some((Vec2::new(3.0, 4.0), 10.0)));
// A `)` inside a `;` line comment does not close the form, so Space keeps typing text.
send(&mut app, "(+ 1 ; ) ");
assert_eq!(app.cmd.buffer, "(+ 1 ; ) ");
escape(&mut app);
// A free-text prompt still keeps spaces after a closing parenthesis as text.
send(&mut app, "-text 0,0 2.5 0 (3+4) 5");
assert_eq!(app.cmd.buffer, "(3+4) 5");
}
}
+6 -48
View File
@@ -333,9 +333,9 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
} }
"cmdline.input" => { "cmdline.input" => {
let text = s("text").unwrap_or(""); let text = s("text").unwrap_or("");
let before = app.session.log_mark(); let before = app.session.log.len();
let error = app.cmdline(text); let error = app.cmdline(text);
let out: Vec<String> = app.session.log_since(before).to_vec(); let out: Vec<String> = app.session.log.iter().skip(before).cloned().collect();
let mut st = cmdline_state(app); let mut st = cmdline_state(app);
if let Some(o) = st.as_object_mut() { if let Some(o) = st.as_object_mut() {
o.insert("output".into(), json!(out)); o.insert("output".into(), json!(out));
@@ -346,16 +346,16 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
ok(st) ok(st)
} }
"cmdline.script" => { "cmdline.script" => {
let before = app.session.log_mark(); let before = app.session.log.len();
let r = app.session.script(s("text").unwrap_or("")).map_err(|e| e.to_string()); let r = app.session.script(s("text").unwrap_or("")).map_err(|e| e.to_string());
let out: Vec<String> = app.session.log_since(before).to_vec(); let out: Vec<String> = app.session.log.iter().skip(before).cloned().collect();
match r { match r {
Ok(()) => ok(json!({"output": out, "state": cmdline_state(app)})), Ok(()) => ok(json!({"output": out, "state": cmdline_state(app)})),
Err(e) => err(e), Err(e) => err(e),
} }
} }
"cmdline.key" => { "cmdline.key" => {
let before = app.session.log_mark(); let before = app.session.log.len();
let error = match s("key").unwrap_or("enter").to_ascii_lowercase().as_str() { let error = match s("key").unwrap_or("enter").to_ascii_lowercase().as_str() {
"escape" | "esc" => { "escape" | "esc" => {
app.paste.cancel(); app.paste.cancel();
@@ -368,7 +368,7 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
if let Some(e) = &error { if let Some(e) = &error {
app.session.echo(e.clone()); app.session.echo(e.clone());
} }
let out: Vec<String> = app.session.log_since(before).to_vec(); let out: Vec<String> = app.session.log.iter().skip(before).cloned().collect();
let mut st = cmdline_state(app); let mut st = cmdline_state(app);
if let Some(o) = st.as_object_mut() { if let Some(o) = st.as_object_mut() {
o.insert("output".into(), json!(out)); o.insert("output".into(), json!(out));
@@ -975,48 +975,6 @@ mod tests {
assert_eq!(render_reply(b"abc", 7, 5, None, true)["truncated"], true); assert_eq!(render_reply(b"abc", 7, 5, None, true)["truncated"], true);
} }
/// #3643: the command-line methods report the lines a request printed, also when the command
/// history is trimmed from the front meanwhile.
#[test]
fn cmdline_output_survives_the_history_trim() {
// Echo lines until the next one trims the history: grow it to its first trim, then back
// up to the length it had just before it.
fn fill(app: &mut CadApp) {
let mut top = 0;
loop {
let len = app.session.log.len();
app.session.echo("filler");
if app.session.log.len() < len {
break;
}
top = app.session.log.len();
}
while app.session.log.len() < top {
app.session.echo("filler");
}
}
// The `y` lines a request reports; it reports nothing from before it.
fn ys(app: &mut CadApp, method: &str, params: Value) -> usize {
let (req, _rx) = ControlRequest::new(method, params);
let Outcome::Done(r) = handle(app, &egui::Context::default(), &req) else { panic!("{method} took a screenshot") };
let out = r["result"]["output"].as_array().cloned().unwrap_or_default();
assert!(!out.contains(&json!("filler")), "{method}: {r}");
out.iter().filter(|l| *l == "y").count()
}
let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default());
app.session.new_drawing(false);
let lines = "(repeat 20 (princ \"y\") (terpri))";
fill(&mut app);
assert_eq!(ys(&mut app, "cmdline.script", json!({"text": format!("{lines}\n")})), 20);
fill(&mut app);
assert_eq!(ys(&mut app, "cmdline.input", json!({"text": lines})), 20);
// Enter repeats a LISP command that prints them.
ys(&mut app, "cmdline.input", json!({"text": format!("(defun c:ys () {lines} (princ))")}));
ys(&mut app, "cmdline.input", json!({"text": "ys"}));
fill(&mut app);
assert_eq!(ys(&mut app, "cmdline.key", json!({"key": "enter"})), 20);
}
/// The reply to a `ui.render` request in an app showing one line along y = 0: colour 7, or /// The reply to a `ui.render` request in an app showing one line along y = 0: colour 7, or
/// red on a red layer. /// red on a red layer.
fn render_line(red: bool, params: Value) -> Value { fn render_line(red: bool, params: Value) -> Value {

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