Compare commits

..
Author SHA1 Message Date
skylartaylor eeca965d35 Merge pinned main into regression-test follow-up 2026-11-21 02:04:01 +01:00
skylartaylor 285059ce98 Tests: one synthetic TrueType builder for render and PDF, and the exact LAYER cap
Sonar's duplicate-lines gate flags 84 of the 334 new lines (25.15% against a 3% limit): the render
level-of-detail fixture's `fixture_font_bytes` and the PDF writer's `test_font` build the same sfnt
tables, so the two suites carried a copy each.

Both now build their fonts with `crates/fonts/tests/support/sfnt.rs`, which the two suites include
with `#[path]`. The fonts layer owns the table format it reads (`crates/fonts/src/ttf.rs`), so the
skeleton lives beside its tests and neither consumer is turned into a published API or a dependency;
no Cargo entry changes. The glyph shapes (`ring`), the cmap ranges and the metrics each font records
stay at the caller: the render fixture keeps its two 128-point contours with the counter wound the
other way, its 1000-unit em and 700-unit cap height, and the PDF fixtures keep their three fonts.

The font files are byte-identical before and after the refactor: render 1704 bytes, sha256
83b9914cdf6e704df1ca5851ecefc98708c947b0d5be818cf5b6282761d31db0; PDF embeddable 484 bytes
2711cc7394b2057ba7e6bee22bb25a6c25edd4ecec0d35ba326759a04fcdefb9 and `fsType=2` restricted 484
bytes 3e6b534115429e8cbfdefd97e40ebdeb874222fcd7929f69b02d261cef622db4, one byte apart at OS/2
`fsType`; and the deliberately short `hmtx` 476 bytes
dbcc548f59a4d3e414deb959014b8548632a7fa66fe12201895cdcbe6e66a000, whose `hhea` still declares three
metrics while `hmtx` holds one.

The DXF LAYER cap test asserted `<= 1_000_000` and `> 900_000`, which lets up to 99,999 valid
records go missing unnoticed. It now asserts exactly the million layers the parser keeps, written as
a literal so a changed constant fails the test instead of following it, with a records-specific
message. Removing the guard reads 1000101 layers; a cap of 950,000 reads 950,000.
2026-11-15 07:30:08 +01:00
skylar taylor-barrick 68fbf2a58d #618: test that OFFSET takes a clicked distance and picks its source under grid snap
OFFSET only accepted a typed distance, and with grid snap on a click meant to pick the source object was moved to the nearest grid point.

The engine test clicks two points for the distance and checks the second-point prompt and its base, the guide line in the preview, OFFSETDIST and the resulting offset. The canvas test does the same through grid-snapped clicks, then picks the source line and checks the side click puts the copy 5 units up, that OFFSET asks for the next object and that Enter ends it. Both live in the per-crate integration-test binary (#1989).

Without the fix the engine and canvas tests stay at the distance prompt; with only the cursor's point-prompt test reverted the canvas test never picks the line.
2026-11-15 05:59:54 +01:00
skylar taylor-barrick ee25f48c7b #651: test that small filled text is simplified on screen and keeps full detail in plots
Filled TrueType text was triangulated at full outline detail at every zoom, which froze the canvas on pages of small text.

The test draws four O glyphs in a font built in the test itself (a 128-point ring registered through `cadcraft_fonts::ttf::register`), so it needs no installed font and no font file in the repository, and it never skips. At 10 px per cap height the rings are simplified and the shapes keep their extent; with an em under two pixels each glyph is the ink's box, two triangles; a plot keeps every point. Without the fix the on-screen build has the plot's 1024 triangles.

`crates/render/src/text.rs` gains the same policy without any font: `detail` returns Full for a plot, Box for an em under two pixels and Reduced for a small one, and `simplify` drops the points of a flattened curve at a coarse band and keeps them at a fine one.
2026-11-15 05:59:54 +01:00
skylar taylor-barrick a6981415bf #1336: test that the DXF LAYER table stops at the record cap
The LAYER, LTYPE, STYLE and DIMSTYLE tables had no record cap, unlike VIEW, UCS and VPORT. The test reads a DXF with over a million LAYER records and checks the layer list stays at the cap; without the guard it holds every record (1000102 layers). The other three tables scan their lists linearly per record, so a million-record file is too slow to build in a test and they stay uncovered.
2026-11-15 05:53:20 +01:00
31 changed files with 549 additions and 1039 deletions
-4
View File
@@ -85,9 +85,6 @@ pub struct Foreign {
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
/// later save must not take it for this one (#2471).
pub version: Option<String>,
/// The file's registered applications (APPID names as read, in file order). Saving writes
/// them all back, whether or not any xdata still names them.
pub appids: Vec<String>,
}
impl Foreign {
@@ -106,7 +103,6 @@ impl Foreign {
&& self.targets.is_empty()
&& self.class_order.is_empty()
&& self.data_store.is_empty()
&& self.appids.is_empty()
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
-14
View File
@@ -821,18 +821,6 @@ pub struct PageSetup {
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
#[serde(skip_serializing_if = "Option::is_none")]
pub image_origin: Option<Vec2>,
/// The plot layout flags (DXF group 70 of AcDbPlotSettings) as the file had them. Saving keeps
/// the bits CADCraft doesn't model (plot paper space last, plot with plot styles, standard
/// scale and the rest) as read instead of forcing its defaults (#3227); `None` for page setups
/// made in CADCraft.
#[serde(skip)]
pub file_plot_flags: Option<i64>,
/// The standard scale the file chose (DXF group 75, such as 25 for 1:50) and the plot scale it
/// was read with. While the scale is unchanged, saving keeps that choice and the standard scale
/// flag instead of writing the scale as a custom one; `None` for a custom scale, scaled to
/// fit, or a page setup made in CADCraft.
#[serde(skip)]
pub file_standard_scale: Option<(i64, f64)>,
}
impl Default for PageSetup {
@@ -856,8 +844,6 @@ impl Default for PageSetup {
paper_mm: None,
file_paper: None,
image_origin: None,
file_plot_flags: None,
file_standard_scale: None,
}
}
}
-4
View File
@@ -1,5 +1,4 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
@@ -37,9 +36,6 @@ pub fn specs() -> Vec<CommandSpec> {
// Typed with nothing selected it asks for objects, as in AutoCAD, rather than converting none.
.interactive(|_| Ok(Box::new(SelectRun::new("region", "REGION")))),
CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))),
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
-53
View File
@@ -29,59 +29,6 @@ fn hatches(s: &Session, p: &Value) -> Result<Vec<Handle>> {
Ok(out)
}
/// Most polylines one HATCHGENERATEBOUNDARY call creates.
const MAX_GENERATED: usize = 10_000;
/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of
/// the selected hatches, at each hatch's height. The hatches are not changed: an associative
/// hatch stays linked to its own boundary objects and is not linked to the new polylines.
pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result<Value> {
let selected = targets(s, p)?;
// The polylines go to the current space, so every hatch must be there too.
let space = s.space();
let mut loops = Vec::new();
let mut found = false;
// A hatch named twice gets its boundary once.
let mut seen = std::collections::HashSet::new();
{
let d = s.doc()?;
for h in selected {
let Some(e) = d.entity(h) else { continue };
let EntityKind::Hatch(x) = &e.kind else { continue };
if !seen.insert(h) {
continue;
}
found = true;
if d.space_of(h).as_ref() != Some(&space) {
return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex())));
}
// Every selected hatch counts: none is left out of a call that succeeds. Compared
// against the room left, so a hostile loop count can't overflow the sum.
if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) {
return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches")));
}
// The elevation runs along the hatch's normal: one facing down Z (mirrored) lies at its
// negative, where the polyline, facing up, goes.
let z = if e.common.extrusion.z < 0.0 { -x.elevation } else { x.elevation };
loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), z)));
}
}
if !found {
return Err(bad("hatchgenerateboundary", "select one or more hatches"));
}
// Everything is checked before anything is added, so a refused call leaves nothing behind.
let mut created = Vec::new();
for (vs, elevation) in loops {
let mut kind = lwpoly(vs, true);
if let EntityKind::LwPolyline(pl) = &mut kind {
pl.elevation = elevation;
}
created.push(s.add_entity(kind)?.hex());
}
let n = created.len();
Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") }))
}
fn outline(l: &HatchLoop) -> Vec<Vec2> {
Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3)
}
@@ -235,7 +235,6 @@ pub const NO_FILES: &[&str] = &[
"boundary",
"region",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
"overkill",
"block",
+13 -4
View File
@@ -126,14 +126,23 @@ pub fn snap_name(m: u32) -> &'static str {
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
/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest
/// first, then deferred snaps, then Nearest), without repeats.
/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks
/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats.
pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option<Vec2>, deferred: bool) -> Vec<SnapHit> {
if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 {
return Vec::new();
}
crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred)
let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred);
let extra = osmode & mode::HATCH;
let mut per_mode: Vec<SnapHit> = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect();
per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor)));
let mut out: Vec<SnapHit> = osnap(osmode).into_iter().collect();
for h in per_mode {
if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) {
out.push(h);
}
}
out
}
/// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with.
+60 -144
View File
@@ -72,33 +72,6 @@ impl SnapHit {
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.
@@ -238,14 +211,6 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3
osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred)
}
/// 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
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn osnap_with(
d: &Drawing,
@@ -272,39 +237,19 @@ pub(crate) fn osnap_with_neighborhood(
base: Option<Vec2>,
deferred: bool,
) -> (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) {
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) {
Some((hits, prims)) => (hits, Some(prims)),
None => (Vec::new(), None),
let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) {
Some((hit, prims)) => (hit, Some(prims)),
None => (None, None),
};
let views = viewport::near(d, space, cursor, aperture);
if views.is_empty() {
return (all, near_prims);
return (best, near_prims);
}
let model = Space::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 {
let model_cursor = view.to_model(cursor);
let model_aperture = aperture / view.scale;
@@ -312,7 +257,7 @@ 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()) {
continue;
}
let hits = osnap_in(
let hit = osnap_in(
d,
&model,
&model_ix,
@@ -323,36 +268,15 @@ fn osnap_all_with_neighborhood(
deferred,
&view.viewport.frozen_layers,
Some(view.model_clip),
);
if let Some(hit) = hits.first().and_then(|h| view.hit(*h))
&& pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
)
.and_then(|h| view.hit(h));
if let Some(hit) = hit
&& best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture))
{
pick = Some(hit);
}
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);
best = Some(hit);
}
}
out
(best, near_prims)
}
#[allow(clippy::too_many_arguments)]
@@ -367,11 +291,10 @@ fn osnap_in(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Vec<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default()
) -> Option<SnapHit> {
osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit)
}
/// The snaps near the cursor in one space, best first, and the primitives gathered there.
#[allow(clippy::too_many_arguments)]
fn osnap_in_with_prims(
d: &Drawing,
@@ -384,7 +307,7 @@ fn osnap_in_with_prims(
deferred: bool,
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
) -> Option<(Option<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
@@ -422,8 +345,8 @@ fn osnap_in_with_prims(
}
}
}
let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hits, near_prims))
let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip);
Some((hit, near_prims))
}
fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option<Bounds2> {
@@ -535,8 +458,7 @@ fn gather_in(
Some((cands, near_prims))
}
/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent
/// snaps, the deferred snaps and Nearest.
/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps.
#[allow(clippy::too_many_arguments)]
fn finish(
mut cands: Vec<(u32, Vec2)>,
@@ -547,7 +469,7 @@ fn finish(
base: Option<Vec2>,
deferred: bool,
clip: Option<Bounds2>,
) -> Vec<SnapHit> {
) -> Option<SnapHit> {
// Perpendicular / tangent from the base point.
if let Some(bp) = base {
for p in near_prims {
@@ -585,10 +507,20 @@ fn finish(
}
}
let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p));
let mut hits: Vec<SnapHit> =
cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect();
if base.is_none() && deferred {
hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip));
let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| {
// Prefer more specific modes when nearly equidistant.
let da = snap_score(a.0, a.1, cursor, aperture);
let db = snap_score(b.0, b.1, cursor, aperture);
da.total_cmp(&db)
});
if let Some((m, p)) = best {
return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None });
}
if base.is_none()
&& deferred
&& let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip)
{
return Some(h);
}
if osmode & mode::NEA != 0 {
// The closest point of all nearby objects, whatever their drawing order.
@@ -608,13 +540,12 @@ fn finish(
}
}
if let Some((_, p)) = nb {
hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None });
}
}
ranked(hits, cursor, aperture)
None
}
/// Prefer more specific modes when nearly equidistant.
fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 {
point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 }
}
@@ -917,11 +848,9 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim {
}
}
/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and
/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the
/// perpendicular on the same circle.
fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option<Bounds2>) -> Vec<SnapHit> {
let mut hits = Vec::new();
/// 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 },
@@ -930,28 +859,32 @@ fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip:
Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir },
_ => continue,
};
// Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray
// anywhere.
let at = match curve {
SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor),
SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor),
SnapCurve::Line { a, b } => {
let l = cadcraft_geom::Line::new(a, b);
if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }
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,
};
if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) {
continue;
}
let modes: &[(u32, &'static str)] = match curve {
SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")],
SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")],
};
for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) {
hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) });
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 }) }));
}
}
hits
best.map(|(_, h)| h)
}
/// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two
@@ -1188,23 +1121,6 @@ mod tests {
assert_eq!(h.name, "Intersection");
}
/// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection
/// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap`
/// picks.
#[test]
fn osnap_all_ranks_every_candidate() {
let d = drawing();
let modes = 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);
assert_eq!(all.iter().map(|h| h.mode).collect::<Vec<_>>(), [mode::INT, mode::MID, mode::NEA], "{all:?}");
assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point);
// On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot.
let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true);
let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect();
assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}");
assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty());
}
#[test]
fn center_quadrant_tangent() {
let d = drawing();
@@ -1,205 +0,0 @@
//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are.
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline};
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
fn hatch(s: &Session, h: &str) -> Hatch {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::Hatch(x) => x.clone(),
k => panic!("not a hatch: {k:?}"),
}
}
fn poly(s: &Session, h: &str) -> LwPolyline {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::LwPolyline(p) => p.clone(),
k => panic!("not a polyline: {k:?}"),
}
}
fn handle(v: &Value) -> String {
v["handle"].as_str().unwrap().to_string()
}
fn handles(v: &Value) -> Vec<String> {
v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect()
}
fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String {
handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap())
}
fn count(s: &Session) -> usize {
s.doc().unwrap().model.iter().count()
}
#[test]
fn generates_a_closed_polyline_around_a_hatch_without_its_outline() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap());
s.execute("erase", &json!({ "handles": [r] })).unwrap();
let before = hatch(&s, &h);
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
let new = handles(&v);
assert_eq!(new.len(), 1);
let p = poly(&s, &new[0]);
assert!(p.closed);
assert_eq!(p.vertices, before.loops[0].vertices);
assert_eq!(hatch(&s, &h), before, "the hatch is not changed");
s.execute("undo", &json!({})).unwrap();
assert_eq!(count(&s), 1, "one undo step removes what was generated");
}
#[test]
fn islands_get_their_own_polylines() {
let mut s = Session::new();
rect(&mut s, [0.0, 0.0], [20.0, 20.0]);
rect(&mut s, [5.0, 5.0], [10.0, 10.0]);
let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap());
assert_eq!(hatch(&s, &h).loops.len(), 2);
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
assert_eq!(handles(&v).len(), 2);
}
#[test]
fn every_selected_hatch_gets_its_boundary() {
let mut s = Session::new();
let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]);
let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap());
let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap();
assert_eq!(handles(&v).len(), 2);
}
#[test]
fn a_hatch_named_twice_gets_one_boundary() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone(), h] })).unwrap();
assert_eq!(handles(&v).len(), 1);
}
#[test]
fn an_associative_hatch_stays_linked_to_its_own_boundary() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap());
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap();
let p = handles(&v)[0].clone();
// Moving the generated polyline leaves the hatch where it is.
s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap();
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0);
// Moving the original rectangle still moves the hatch.
s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap();
assert!(hatch(&s, &h).associative);
assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0);
}
#[test]
fn boundaries_keep_the_hatch_elevation() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
if let EntityKind::Hatch(x) = &mut e.kind {
x.elevation = 300.0;
}
})
.unwrap();
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0);
}
/// A mirrored hatch (normal 0,0,-1, as exploding a mirrored block makes) at elevation 300 lies at
/// world Z -300; its boundary, facing up, goes there too, not to +300.
#[test]
fn a_mirrored_hatchs_boundary_keeps_its_world_height() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
e.common.extrusion = cadcraft_engine::geom::Vec3::new(0.0, 0.0, -1.0);
if let EntityKind::Hatch(x) = &mut e.kind {
x.elevation = 300.0;
}
})
.unwrap();
let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap();
let new = Handle::parse_hex(&handles(&v)[0]).unwrap();
let e = s.doc().unwrap().entity(new).unwrap().clone();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
assert_eq!(e.common.extrusion.z.signum() * p.elevation, -300.0);
}
#[test]
fn refuses_a_hatch_in_another_space_and_adds_nothing() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let before = s.doc().unwrap().entity_count();
let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err();
assert!(e.to_string().contains("not in the current space"), "{e}");
assert_eq!(s.doc().unwrap().entity_count(), before);
}
#[test]
fn refuses_more_boundaries_than_the_limit_and_adds_nothing() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
// One hatch with more loops than one call may turn into polylines.
s.doc_mut()
.unwrap()
.modify_entity(Handle::parse_hex(&h).unwrap(), |e| {
if let EntityKind::Hatch(x) = &mut e.kind {
let l = x.loops[0].clone();
x.loops = vec![l; 10_001];
}
})
.unwrap();
let before = count(&s);
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err());
assert_eq!(count(&s), before);
}
#[test]
fn needs_a_hatch() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err());
assert_eq!(count(&s), 1, "nothing is added");
}
#[test]
fn runs_at_once_on_selected_hatches() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.set_selection(vec![Handle::parse_hex(&h).unwrap()]);
s.start("hatchgenerateboundary").unwrap();
assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt");
assert_eq!(count(&s), 3);
}
#[test]
fn asks_for_hatches_without_a_selection() {
let mut s = Session::new();
let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]);
let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap());
s.set_selection(Vec::new());
s.start("hatchgenerateboundary").unwrap();
assert!(s.current_prompt().is_some());
s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap();
s.input(Input::Enter).unwrap();
assert!(s.current_prompt().is_none());
assert_eq!(count(&s), 3);
}
-1
View File
@@ -68,7 +68,6 @@ mod group_selection;
mod groups;
mod hatch_assoc;
mod hatch_dialog_helpers;
mod hatch_generate_boundary;
mod hatch_numeric_validation;
mod hatch_options;
mod helix;
@@ -2,7 +2,7 @@
use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport};
use cadcraft_engine::geom::{Vec2, Vec3};
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all};
use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap};
use cadcraft_engine::{Input, Session};
use serde_json::json;
@@ -278,46 +278,6 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() {
assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none());
}
/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap
/// replaces paper space's only when it scores closer. Tab still reaches the other one.
#[test]
fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() {
let (mut d, paper) = drawing();
// A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50).
d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap();
let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA);
let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap();
assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}");
assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}");
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!(
all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)),
"Tab reaches the viewport's endpoint: {all:?}"
);
}
/// Overlapping viewports can show different model points at one paper point; Tab offers each,
/// since DIST measures in the model units of the viewport picked.
#[test]
fn overlapping_viewports_each_offer_their_model_point() {
let (mut d, paper) = drawing();
// This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0).
edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0));
let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind {
EntityKind::Viewport(vp) => vp.clone(),
_ => panic!("viewport fixture"),
};
vp.view_center = Vec2::new(0.0, 0.0);
vp.id = 3;
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false);
let mut models: Vec<Vec2> =
all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect();
models.sort_by(|a, b| a.x.total_cmp(&b.x));
assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}");
}
#[test]
fn viewport_frozen_layers_do_not_hide_paper_space_geometry() {
let (mut d, paper) = drawing();
+23
View File
@@ -1,7 +1,9 @@
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
use cadcraft_engine::Input;
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use cadcraft_engine::geom::Vec2;
use serde_json::json;
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
@@ -62,6 +64,27 @@ fn offset_multiple_and_undo() {
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
}
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
// (the distance between them) was rejected, and the second click had no distance guide.
#[test]
fn offset_distance_from_two_clicked_points() {
let mut s = one_line();
s.start("offset").unwrap();
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
let p = s.current_prompt().unwrap();
assert!(p.message.contains("second point"), "{}", s.prompt_text());
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
// The guide from the first click to the cursor is the previewed distance.
let guide = s.preview(Vec2::new(20.0, 22.5));
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
s.script("5,0 5,1\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
}
#[test]
fn offset_json_erase_and_layer() {
let mut s = one_line();
+196
View File
@@ -0,0 +1,196 @@
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
//!
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
//! the character map ranges and the metrics a font records stay at the caller that needs them.
fn be16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn be32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A simple glyph, with the point and contour counts `maxp` records for the font.
pub struct Glyph {
bytes: Vec<u8>,
points: usize,
contours: usize,
}
/// `.notdef`: no contours, no bytes.
pub fn notdef() -> Glyph {
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
}
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
let mut g = Vec::new();
be16(&mut g, contours.len() as u16);
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
for v in [box_.0, box_.1, box_.2, box_.3] {
be16(&mut g, v as u16);
}
let mut end = 0u16;
for c in contours {
end = end.saturating_add(c.len() as u16);
be16(&mut g, end.saturating_sub(1));
}
be16(&mut g, 0);
g.extend(std::iter::repeat_n(1u8, points.len()));
let (mut px, mut py) = (0i16, 0i16);
for (x, _) in &points {
be16(&mut g, x.wrapping_sub(px) as u16);
px = *x;
}
for (_, y) in &points {
be16(&mut g, y.wrapping_sub(py) as u16);
py = *y;
}
while g.len() % 4 != 0 {
g.push(0);
}
Glyph { bytes: g, points: points.len(), contours: contours.len() }
}
/// What the callers differ in; every other table field is the same in each font this builds.
pub struct Sfnt<'a> {
/// `glyf` entries, `.notdef` first.
pub glyphs: &'a [Glyph],
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
/// code. The `0xFFFF` segment that ends the map is added here.
pub cmap: &'a [(u16, u16, i16)],
/// The advance width every glyph shares, in em units.
pub advance: u16,
/// The left side bearing every glyph shares.
pub lsb: i16,
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
pub metrics: usize,
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
pub fs_type: u16,
/// `head`'s ink box: xMin, yMin, xMax, yMax.
pub ink_box: [i16; 4],
}
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
/// is a cap height of one unit.
const UNITS_PER_EM: u16 = 1000;
/// The font file `f` describes, as a TrueType file.
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
let mut glyf = Vec::new();
let mut loca = Vec::new();
for g in f.glyphs {
be32(&mut loca, glyf.len() as u32);
glyf.extend_from_slice(&g.bytes);
}
be32(&mut loca, glyf.len() as u32);
let mut head = Vec::new();
be32(&mut head, 0x0001_0000); // version
be32(&mut head, 0x0001_0000); // fontRevision
be32(&mut head, 0); // checkSumAdjustment
be32(&mut head, 0x5F0F_3CF5); // magic
be16(&mut head, 0); // flags
be16(&mut head, UNITS_PER_EM);
head.extend_from_slice(&[0; 16]); // created, modified
for v in f.ink_box {
be16(&mut head, v as u16);
}
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
// `u32`), glyphDataFormat.
for v in [0u16, 8, 2, 1, 0] {
be16(&mut head, v);
}
let mut hhea = Vec::new();
be32(&mut hhea, 0x0001_0000);
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut hhea, v as u16);
}
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
let mut maxp = Vec::new();
be32(&mut maxp, 0x0001_0000);
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
// the composite and instruction maxima after them.
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut maxp, v);
}
let mut hmtx = Vec::new();
for _ in 0..f.metrics {
be16(&mut hmtx, f.advance);
be16(&mut hmtx, f.lsb as u16);
}
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
// the caller's segments and the `0xFFFF` one that ends it.
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
let seg_count = segs.len() as u32;
let seg_selector = seg_count.ilog2();
let seg_search_range = 2 * (1 << seg_selector);
let mut sub = Vec::new();
be16(&mut sub, 4); // format
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
be16(&mut sub, 0); // language
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
be16(&mut sub, v);
}
for s in &segs {
be16(&mut sub, s.1);
}
be16(&mut sub, 0); // reservedPad
for s in &segs {
be16(&mut sub, s.0);
}
for s in &segs {
be16(&mut sub, s.2 as u16);
}
for _ in &segs {
be16(&mut sub, 0); // idRangeOffset
}
let mut cmap = Vec::new();
for v in [0u16, 1, 3, 1] {
be16(&mut cmap, v);
}
be32(&mut cmap, 12); // the subtable, straight after the records
cmap.extend_from_slice(&sub);
let mut os2 = vec![0u8; 78];
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
tables.sort_by_key(|t| *t.0);
let mut out = Vec::new();
be32(&mut out, 0x0001_0000); // sfnt version 1.0
let num_tables = tables.len() as u32;
let table_selector = num_tables.ilog2();
let dir_search_range = 16 * (1 << table_selector);
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
be16(&mut out, v);
}
let mut off = 12 + 16 * tables.len();
for (t, d) in &tables {
out.extend_from_slice(*t);
be32(&mut out, 0); // checkSum: the readers here do not verify it
be32(&mut out, off as u32);
be32(&mut out, d.len() as u32);
off += d.len().div_ceil(4) * 4;
}
for (_, d) in &tables {
out.extend_from_slice(d);
while out.len() % 4 != 0 {
out.push(0);
}
}
out
}
+4 -12
View File
@@ -457,10 +457,6 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
if !f.is_empty() {
f.version = file_version(secs);
}
// Added after the version: registered applications alone are no kept objects whose groups
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
f.appids = appids.take(MAX_OBJECTS).collect();
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
if !f.is_empty() || !f.handles.is_empty() {
@@ -1271,7 +1267,7 @@ pub(crate) fn finish(
join_entries(&map, b, kept, &mut out);
}
}
add_appids(&mut out, &f.appids);
add_appids(&mut out);
let top = max_handle(&out).saturating_add(1);
if let Some(t) = seed_index(&out).and_then(|i| out.get_mut(i))
&& Handle::parse_hex(&t.str()).is_none_or(|h| h.0 < top)
@@ -1597,13 +1593,9 @@ fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>)
}
}
/// APPID records for every application with xdata in the file and every one the file read had
/// (`kept`), added to the APPID table.
fn add_appids(out: &mut Vec<Tag>, kept: &[String]) {
let mut used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
for name in kept.iter().filter(|n| !n.is_empty()) {
used.entry(up(name)).or_insert_with(|| name.clone());
}
/// APPID records for every application with xdata in the file, added to the APPID table.
fn add_appids(out: &mut Vec<Tag>) {
let used: BTreeMap<String, String> = out.iter().filter(|t| t.code == 1001).map(|t| (up(&t.str()), t.str().trim().to_string())).collect();
let recs = written_records(out);
let Some(table) = recs.iter().position(|r| {
r.sec == "TABLES" && r.kind == "TABLE" && val(out.get(r.start + 1..r.end).unwrap_or(&[]), 2).is_some_and(|n| up(&n) == "APPID")
+6 -28
View File
@@ -88,7 +88,6 @@ fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option<EntityKind> {
// In a tilted plane: drawn as seen from above, at the vertices' mean height, its
// vertices now plan coordinates.
(verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0);
thickness_along_z(c);
c.extrusion = Vec3::Z;
} else if c.extrusion.z < 0.0 {
for v in &mut verts {
@@ -578,7 +577,7 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
break;
}
}
let mut c = common(t);
let c = common(t);
let mut extra: Vec<EntityKind> = Vec::new();
let k = if flags & 64 != 0 {
// Face records that name a missing vertex (or fewer than three) are dropped: they draw
@@ -600,26 +599,13 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
} else if flags & 8 != 0 {
EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 })
} else {
// A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point:
// in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it.
let closed = flags & 1 != 0;
let mut vertices: Vec<PolyVertex> = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect();
let mut elevation = t.p(10).z;
if tilted(c.extrusion, run_points(&vertices, elevation, closed)) {
(vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed);
thickness_along_z(&mut c);
c.extrusion = Vec3::Z;
} else if c.extrusion.z < 0.0 {
for v in &mut vertices {
v.p.x = -v.p.x;
v.bulge = -v.bulge;
}
}
// A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE.
let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 };
EntityKind::LwPolyline(LwPolyline {
vertices,
closed,
vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(),
closed: flags & 1 != 0,
const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0),
elevation,
elevation: t.p(10).z,
plinegen: flags & 128 != 0,
})
};
@@ -728,11 +714,3 @@ fn helix(tags: &[Tag]) -> Helix {
}
.sanitized()
}
/// A polyline drawn as seen from above gets the normal +Z: its thickness keeps the side of Z it
/// extruded toward, which the normal it is losing said.
fn thickness_along_z(c: &mut Common) {
if c.extrusion.z < 0.0 {
c.thickness = -c.thickness;
}
}
-9
View File
@@ -421,8 +421,6 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
// Plot layout flags: 2 display plot styles, 4 centred, 16 standard scale (75 = 0: scaled
// to fit), 128 lineweights.
if let Some(flags) = t.i(70) {
// Kept to be written back (a 16-bit group: only those bits).
p.file_plot_flags = Some(flags & 0xFFFF);
p.show_plot_styles = flags & 2 != 0;
p.center = flags & 4 != 0;
p.lineweights = flags & 128 != 0;
@@ -434,13 +432,6 @@ pub(super) fn page_setup(t: &T, tags: &[Tag]) -> PageSetup {
if let Some(s) = pos(ratio).or_else(|| pos(t.f(147))) {
p.scale = s;
}
// A standard scale (flag 16, group 75 above 0: 0 is scaled to fit, the DXF Reference lists
// 1 to 32), kept with the scale it stands for so a save can tell it was not changed.
if t.i(70).is_some_and(|f| f & 16 != 0)
&& let Some(code) = t.i(75).filter(|c| (1..=32).contains(c))
{
p.file_standard_scale = Some((code, p.scale));
}
p.plot_area = match t.i(74) {
Some(0) => "display",
Some(1) => "extents",
+7 -22
View File
@@ -108,10 +108,7 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
EntityKind::Line(l) => {
w.s(0, "LINE");
common(w, e, owner, paper, "AcDbLine");
// Along the normal written with it (210 below), as read.
if e.common.thickness != 0.0 {
w.f(39, e.common.thickness);
}
thickness(w, e);
w.p(10, l.a);
w.p(11, l.b);
extrusion(w, e);
@@ -159,13 +156,8 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if p.const_width > 0.0 {
w.f(43, p.const_width);
}
// The elevation runs along the polyline's normal, which isn't written: one facing down
// Z is at the elevation's negative. That is exact for a normal of 0,0,-1 only; a tilted
// one pointing partly down is flipped the same way (the reader brings tilted polylines
// into plan with normal Z, so only other sources make one).
let elevation = if e.common.extrusion.z < 0.0 { -p.elevation } else { p.elevation };
if elevation != 0.0 {
w.f(38, elevation);
if p.elevation != 0.0 {
w.f(38, p.elevation);
}
thickness(w, e);
for v in &p.vertices {
@@ -617,10 +609,7 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if let EntityKind::Hatch(h) = &e.kind {
w.s(0, "HATCH");
common(w, e, owner, paper, "AcDbHatch");
// Its elevation runs along its normal, written as Z: one facing down is at the negative.
// Exact for a normal of 0,0,-1; the reader brings a tilted hatch into plan with normal Z.
let elevation = if e.common.extrusion.z < 0.0 { -h.elevation } else { h.elevation };
w.p(10, Vec3::new(0.0, 0.0, elevation));
w.p(10, Vec3::new(0.0, 0.0, h.elevation));
w.p(210, Vec3::Z);
w.s(2, &h.pattern);
w.i(70, i64::from(h.solid));
@@ -840,14 +829,10 @@ fn gradient(w: &mut W, g: &Gradient) {
w.s(1000, g.color2.name());
}
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set. They
/// are written with no normal, so they extrude along Z: one whose normal points down Z extrudes
/// the other way, and its thickness changes sign. That is exact for a normal of 0,0,-1; a tilted
/// one pointing partly down only gets the closer of the two directions.
/// Group 39 (thickness) of the entities whose DXF Reference record has one; only when set.
fn thickness(w: &mut W, e: &Entity) {
let t = if e.common.extrusion.z < 0.0 { -e.common.thickness } else { e.common.thickness };
if t != 0.0 {
w.f(39, t);
if e.common.thickness != 0.0 {
w.f(39, e.common.thickness);
}
}
+8 -22
View File
@@ -413,23 +413,6 @@ struct LayoutWriteData<'a> {
limits: Option<(Vec2, Vec2)>,
}
/// The plot layout flags (AcDbPlotSettings group 70) for `page`. The bits CADCraft models come
/// from the page: 2 display plot styles, 4 centred, 128 lineweights, and 16 standard scale where
/// the scale decides it (scaled to fit: set; a custom scale: clear). The rest are kept as the file
/// had them (#3227); a page CADCraft made gets 512 (plot paper space last) and 32 (plot with plot
/// styles), and 16 when its scale is standard.
fn plot_layout_flags(page: &PageSetup, standard: bool) -> i64 {
const MODELED: i64 = 2 | 4 | 128;
const STANDARD_SCALE: i64 = 16;
let kept = match page.file_plot_flags {
Some(f) if page.scale_to_fit => (f & !MODELED) | STANDARD_SCALE,
Some(f) if !standard => f & !MODELED & !STANDARD_SCALE,
Some(f) => f & !MODELED,
None => 512 | 32 | if standard { STANDARD_SCALE } else { 0 },
};
kept | if page.lineweights { 128 } else { 0 } | if page.center { 4 } else { 0 } | if page.show_plot_styles { 2 } else { 0 }
}
fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) {
let d = context.drawing;
let layout_dict = context.dictionary;
@@ -443,10 +426,13 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
// Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units
// per 143 drawing units).
let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 };
// The file's standard scale (such as 1:50) while the scale is still the one read with it.
let file_standard = page.file_standard_scale.filter(|&(_, s)| !page.scale_to_fit && s == scale).map(|(code, _)| code);
let standard = page.scale_to_fit || scale == 1.0 || file_standard.is_some();
let plot_flags = plot_layout_flags(page, standard);
let standard = page.scale_to_fit || scale == 1.0;
let plot_flags = 512
| 32
| if standard { 16 } else { 0 }
| if page.lineweights { 128 } else { 0 }
| if page.center { 4 } else { 0 }
| if page.show_plot_styles { 2 } else { 0 };
let plot_type = match page.plot_area.as_str() {
"display" => 0,
"extents" => 1,
@@ -488,7 +474,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
w.i(73, rotation);
w.i(74, plot_type);
w.s(7, &page.plot_style_table);
w.i(75, if page.scale_to_fit { 0 } else { file_standard.unwrap_or(16) });
w.i(75, if page.scale_to_fit { 0 } else { 16 });
w.f(147, scale);
// The paper image origin the file had (#2109), else 0,0.
let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO);
+24 -143
View File
@@ -422,6 +422,30 @@ fn hostile_dxf_does_not_panic() {
}
}
// Regression test for #1336: the LAYER table of a DXF had no record cap, so a hostile file could
// grow the layer list without bound (its VIEW/UCS/VPORT peers stop at one million records).
#[test]
fn dxf_layer_table_stops_at_the_record_cap() {
use std::fmt::Write as _;
let records = 1_000_100;
let mut text = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n");
for i in 0..records {
let _ = write!(text, "0\nLAYER\n2\nL{i}\n");
}
text.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
let d = read(text.as_bytes(), "layers.dxf").unwrap();
// The exact total, not a range: the layer list stops at 1,000,000 layers, the drawing's own
// default layers counted among them, so a cap that truncates early or late fails as loudly as
// none at all. The count is a literal on purpose -- if the constant changes, this test must fail
// rather than follow it.
assert_eq!(
d.layers.len(),
1_000_000,
"the LAYER table must stop at exactly 1,000,000 layers in total, defaults included, reading {records} records, but kept {}",
d.layers.len()
);
}
#[test]
fn svg_and_png_export() {
let d = sample();
@@ -2683,84 +2707,6 @@ fn mirrored_2d_polyline_extrusion_flips_x_and_bulge() {
assert_eq!(got, vec![(-1.0, 0.0, -1.0), (-3.0, 0.0, 0.0)]);
}
/// Objects whose normal is 0,0,-1, at OCS height 5 and most of them 2 thick, keep their world height
/// and the side they extrude to through a save. They are written with no normal (along Z), so an
/// elevation or a thickness written as read put a polyline or a hatch at Z +5 instead of -5, and
/// extruded a circle, point, solid or text up instead of down (AutoCAD 2024 opening the saved file,
/// measured). A line writes its normal, and keeps its thickness as read. The same objects facing up
/// (no normal, and 0,0,1) keep +5 and +2: only a normal pointing down Z changes the sign.
#[test]
fn mirrored_objects_keep_their_world_height_and_thickness_side() {
let records = |normal: &str| {
format!(
"0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n5\n39\n2\n{normal}10\n0\n20\n0\n42\n0.5\n10\n-10\n20\n0\n\
0\nPOLYLINE\n8\n0\n66\n1\n70\n0\n10\n0\n20\n0\n30\n5\n{normal}0\nVERTEX\n8\n0\n10\n0\n20\n10\n0\nVERTEX\n8\n0\n10\n-10\n20\n10\n0\nSEQEND\n\
0\nCIRCLE\n8\n0\n10\n-10\n20\n5\n30\n5\n40\n5\n39\n2\n{normal}\
0\nARC\n8\n0\n10\n-30\n20\n5\n30\n5\n40\n5\n50\n180\n51\n270\n{normal}\
0\nPOINT\n8\n0\n10\n-40\n20\n0\n30\n5\n39\n2\n{normal}\
0\nSOLID\n8\n0\n10\n50\n20\n0\n30\n5\n11\n60\n21\n0\n31\n5\n12\n50\n22\n5\n32\n5\n13\n60\n23\n5\n33\n5\n39\n2\n{normal}\
0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n5\n{normal}2\nSOLID\n70\n1\n71\n0\n91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n\
10\n70\n20\n0\n10\n80\n20\n0\n10\n80\n20\n5\n10\n70\n20\n5\n97\n0\n75\n0\n76\n1\n98\n0\n\
0\nTEXT\n8\n0\n10\n-90\n20\n0\n30\n5\n40\n2\n1\nA\n39\n2\n{normal}\
0\nLINE\n8\n0\n39\n2\n10\n0\n20\n20\n30\n3\n11\n10\n21\n20\n31\n3\n{normal}"
)
};
let (down, up) = ("210\n0\n220\n0\n230\n-1\n", "210\n0\n220\n0\n230\n1\n");
let text = format!("0\nSECTION\n2\nENTITIES\n{}{}{}0\nENDSEC\n0\nEOF\n", records(down), records(""), records(up));
// Each object's kind, world height and thickness along world Z.
let place = |d: &Drawing| -> Vec<(&'static str, f64, f64)> {
d.model
.iter()
.map(|e| {
let n = e.common.extrusion.z.signum();
let (kind, z) = match &e.kind {
EntityKind::LwPolyline(p) => ("polyline", n * p.elevation),
EntityKind::Circle(c) => ("circle", c.center.z),
EntityKind::Arc(a) => ("arc", a.center.z),
EntityKind::Point(p) => ("point", p.p.z),
EntityKind::Solid(s) => ("solid", s.corners[0].z),
EntityKind::Hatch(h) => ("hatch", n * h.elevation),
EntityKind::Text(t) => ("text", t.insert.z),
EntityKind::Line(l) => ("line", l.a.z),
_ => ("other", f64::NAN),
};
(kind, z, n * e.common.thickness)
})
.collect()
};
let d = read(text.as_bytes(), "m.dxf").unwrap();
let mut want = vec![
("polyline", -5.0, -2.0),
("polyline", -5.0, 0.0),
("circle", -5.0, -2.0),
("arc", -5.0, 0.0),
("point", 5.0, -2.0),
("solid", -5.0, -2.0),
("hatch", -5.0, 0.0),
("text", -5.0, -2.0),
("line", 3.0, -2.0),
];
let facing_up = [
("polyline", 5.0, 2.0),
("polyline", 5.0, 0.0),
("circle", 5.0, 2.0),
("arc", 5.0, 0.0),
("point", 5.0, 2.0),
("solid", 5.0, 2.0),
("hatch", 5.0, 0.0),
("text", 5.0, 2.0),
("line", 3.0, 2.0),
];
want.extend(facing_up);
want.extend(facing_up);
assert_eq!(place(&d), want, "as read");
let out = write(&d, "m.dxf").unwrap();
assert_eq!(place(&read(&out, "m.dxf").unwrap()), want, "after a save");
let pairs = dxf_pairs(std::str::from_utf8(&out).unwrap());
let lines: Vec<_> = dxf_records(&pairs, "LINE").into_iter().map(|l| (group(l, "39"), group(l, "230"))).collect();
assert_eq!(lines, [(Some("2.0"), Some("-1.0")), (Some("2.0"), None), (Some("2.0"), None)]);
}
#[test]
fn mirrored_hatch_extrusion_flips_boundary() {
// HATCH boundaries are OCS: the square (1,0)..(3,2) under extrusion (0,0,-1) lies at (-3,0)..(-1,2).
@@ -2805,20 +2751,6 @@ fn tilted_hatch_turns_its_gradient() {
assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle);
}
/// A tilted polyline with a thickness, its normal pointing partly down Z, still extrudes toward -Z
/// once it is drawn as seen from above and saved with no normal.
#[test]
fn tilted_thick_polyline_keeps_its_extrusion_side() {
let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n39\n5\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
10\n1\n20\n0\n10\n3\n20\n2\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "p.dxf").unwrap();
let e = d.model.iter().next().unwrap();
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z));
let back = roundtrip(&d);
let e = back.model.iter().next().unwrap();
assert_eq!((e.common.thickness, e.common.extrusion), (-5.0, Vec3::Z), "saved with no normal, it still extrudes toward -Z");
}
/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices.
#[test]
fn tilted_straight_lwpolyline_keeps_its_widths() {
@@ -2933,57 +2865,6 @@ fn tilted_lwpolyline_is_drawn_as_seen_from_above() {
assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::<Vec<_>>(), vec![1.0, 1.0]);
}
/// A 2D POLYLINE (heavy polyline) in a tilted plane is drawn as seen from above, like a
/// LWPOLYLINE: before, its OCS points were taken for world coordinates. With extrusion
/// (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and y = (0, √3/2, 1/2), and the elevation of 2
/// moves the plane by twice the normal, (0, 1, -√3): the square (1,0)..(3,2) lies over
/// (-3,1)..(-1,1+√3), its corners at a mean height of 1/2 - √3.
#[test]
fn tilted_2d_polyline_is_drawn_as_seen_from_above() {
let square = |n: &str| {
format!(
"0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n2\n70\n1\n{n}\
0\nVERTEX\n8\n0\n10\n1\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n2\n\
0\nVERTEX\n8\n0\n10\n1\n20\n2\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n"
)
};
let d = read(square("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap();
let b = d.extents(&Space::Model);
let r3 = 3f64.sqrt();
for (got, want) in [(b.min.x, -3.0), (b.min.y, 1.0), (b.max.x, -1.0), (b.max.y, 1.0 + r3)] {
assert!((got - want).abs() < 1e-9, "extents {b:?}");
}
let e = d.model.iter().next().unwrap();
assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now");
let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") };
assert!((p.elevation - (0.5 - r3)).abs() < 1e-9, "the mean height of its corners: {}", p.elevation);
// In plan and in the mirrored plane the polyline stays as it was: mirrored only in x.
let plain = read(square("").as_bytes(), "p.dxf").unwrap();
let b = plain.extents(&Space::Model);
assert!((b.min.x - 1.0).abs() < 1e-9 && (b.max.y - 2.0).abs() < 1e-9, "extents {b:?}");
let mirrored = read(square("210\n0\n220\n0\n230\n-1\n").as_bytes(), "p.dxf").unwrap();
let b = mirrored.extents(&Space::Model);
assert!((b.min.x + 3.0).abs() < 1e-9 && (b.max.x + 1.0).abs() < 1e-9, "extents {b:?}");
assert_eq!(mirrored.model.iter().next().unwrap().common.extrusion, Vec3::new(0.0, 0.0, -1.0));
}
/// A tilted 2D POLYLINE with an arc keeps its shape as seen from above: the half circle from
/// (0,0) to (2,0) is flattened into its half ellipse, in plan x from -2 to 0 and reaching √3/2.
#[test]
fn tilted_2d_polyline_arc_is_flattened() {
let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n0\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\
0\nVERTEX\n8\n0\n10\n0\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n2\n20\n0\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n";
let d = read(text.as_bytes(), "p.dxf").unwrap();
let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None });
assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len());
let b = d.extents(&Space::Model);
// Bulge 1 turns counter-clockwise from (0,0) to (2,0), so the arc runs below its chord, down
// to OCS y -1: plan y -√3/2.
for (got, want) in [(b.min.x, -2.0), (b.max.x, 0.0), (b.min.y, -(3f64.sqrt()) / 2.0), (b.max.y, 0.0)] {
assert!((got - want).abs() < 5e-3, "extents {b:?}");
}
}
/// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards).
fn hatch_edge_extents(edges: &str) -> Bounds2 {
let n = edges.matches("72\n").count();
-74
View File
@@ -1,74 +0,0 @@
//! #3227: saving kept the layout's plot flags only for the bits CADCraft models and forced 512
//! (plot paper space last), 32 (plot with plot styles) and 16 (standard scale) on, so a layout
//! with flags 0 came back as 560, in DXF and in DWG.
use cadcraft_doc::{Drawing, Layout, PageSetup};
use cadcraft_io::{read, write};
/// A drawing with layout SHEET read with plot layout `flags` (lineweights, centring and display
/// plot styles follow them, as the reader sets them).
fn drawing(flags: i64) -> Drawing {
let mut d = Drawing::new_imperial();
let mut l = Layout::new("SHEET", 1);
l.page = PageSetup {
lineweights: flags & 128 != 0,
center: flags & 4 != 0,
show_plot_styles: flags & 2 != 0,
file_plot_flags: Some(flags),
..PageSetup::default()
};
d.layouts.push(l);
d
}
/// The plot layout flags of SHEET after saving `d` as `name` and reading it back.
fn flags_after_save(d: &Drawing, name: &str) -> Option<i64> {
let bytes = write(d, name).unwrap();
let back = read(&bytes, name).unwrap();
back.layouts.iter().find(|l| l.name == "SHEET")?.page.file_plot_flags
}
#[test]
fn plot_layout_flags_are_saved_as_read() {
cadcraft_io::dwg_worker::allow_in_process();
for name in ["sheet.dxf", "sheet.dwg"] {
for flags in [0, 176, 560, 688] {
assert_eq!(flags_after_save(&drawing(flags), name), Some(flags), "{name}: flags {flags}");
}
}
}
#[test]
fn an_unchanged_standard_scale_keeps_its_flag_and_choice() {
cadcraft_io::dwg_worker::allow_in_process();
// Flags 176 with standard scale 25 (1:50): the scale is 0.02, not 1:1, and still standard.
let mut d = drawing(176);
let page = &mut d.layouts.last_mut().unwrap().page;
page.scale = 0.02;
page.file_standard_scale = Some((25, 0.02));
for name in ["sheet.dxf", "sheet.dwg"] {
let back = read(&write(&d, name).unwrap(), name).unwrap();
let page = &back.layouts.iter().find(|l| l.name == "SHEET").unwrap().page;
assert_eq!(page.file_plot_flags, Some(176), "{name}");
assert_eq!(page.file_standard_scale, Some((25, 0.02)), "{name}");
}
// A scale changed after reading is a custom one: 16 is cleared and the choice dropped.
d.layouts.last_mut().unwrap().page.scale = 0.05;
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(160));
}
#[test]
fn the_page_still_decides_the_bits_cadcraft_models() {
// Lineweights turned on and a custom scale chosen after reading flags 16: 128 is set and the
// standard scale bit cleared, the rest kept.
let mut d = drawing(16 | 512);
let page = &mut d.layouts.last_mut().unwrap().page;
page.lineweights = true;
page.scale = 0.02;
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128));
// A page made in CADCraft keeps the defaults (plot paper space last, plot with plot styles,
// standard scale, lineweights).
let mut d = drawing(0);
d.layouts.last_mut().unwrap().page = PageSetup::default();
assert_eq!(flags_after_save(&d, "sheet.dxf"), Some(512 | 128 | 32 | 16));
}
-1
View File
@@ -36,7 +36,6 @@ mod helix_roundtrip;
mod layer_states_acad;
mod layout_limits_roundtrip;
mod layout_paper_units;
mod layout_plot_flags;
mod layout_plot_window;
mod leader_vertex_elevation;
#[cfg(not(target_arch = "wasm32"))]
+1 -2
View File
@@ -257,8 +257,7 @@ pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) {
let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive");
assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name);
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
let setting =
|p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..p.clone() };
let setting = |p: &cadcraft_doc::PageSetup| cadcraft_doc::PageSetup { file_paper: None, ..p.clone() };
assert_eq!(setting(&back.page), setting(&layout.page), "{context}.{}.page", layout.name);
assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name);
compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name));
@@ -112,7 +112,7 @@ fn layout_page_setup_and_paper_view_round_trip() {
for (a, b) in d.layouts.iter().zip(&r.layouts) {
assert_eq!(a.name, b.name);
// The groups 44, 45 and 73 the file stored are provenance, not a setting.
let read = cadcraft_doc::PageSetup { file_paper: None, file_plot_flags: None, file_standard_scale: None, ..b.page.clone() };
let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() };
assert_eq!(a.page, read, "{}", a.name);
assert_eq!(a.view, b.view, "{}", a.name);
}
+22 -128
View File
@@ -3,7 +3,8 @@
//! rotation, width factor and obliquing; fonts whose licence bits forbid embedding, the stroke
//! font and the `text: "geometry"` option keep filled outlines.
//!
//! The fonts are tiny synthetic TrueType files built here (no font files in the repository).
//! The fonts are tiny synthetic TrueType files built by the shared test helper in
//! `crates/fonts/tests/support/sfnt.rs` (no font files in the repository).
use cadcraft_doc::{Common, Drawing, EntityKind, Space, Text, TextStyle, Viewport};
use cadcraft_geom::{Vec2, Vec3};
@@ -15,137 +16,30 @@ mod pdf_read;
use pdf_read::Doc;
// The synthetic TrueType file: the fonts layer's test-only helper, inlined rather than published
// or depended on.
#[path = "../../fonts/tests/support/sfnt.rs"]
mod sfnt;
// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ----------
fn be16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn be32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// A simple glyph: one closed contour of on-curve points.
fn simple_glyph(pts: &[(i16, i16)]) -> Vec<u8> {
let mut g = Vec::new();
let xs: Vec<i16> = pts.iter().map(|p| p.0).collect();
let ys: Vec<i16> = pts.iter().map(|p| p.1).collect();
be16(&mut g, 1);
for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] {
be16(&mut g, v as u16);
}
be16(&mut g, pts.len() as u16 - 1);
be16(&mut g, 0);
g.extend(std::iter::repeat_n(1u8, pts.len()));
let (mut px, mut py) = (0i16, 0i16);
for (x, _) in pts {
be16(&mut g, (x - px) as u16);
px = *x;
}
for (_, y) in pts {
be16(&mut g, (y - py) as u16);
py = *y;
}
while g.len() % 4 != 0 {
g.push(0);
}
g
}
/// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds
/// `metrics` of the three metrics `hhea` declares.
/// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset.
fn test_font(fs_type: u16, metrics: usize) -> Vec<u8> {
let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])];
let mut glyf = Vec::new();
let mut loca = Vec::new();
for g in &glyphs {
be32(&mut loca, glyf.len() as u32);
glyf.extend_from_slice(g);
}
be32(&mut loca, glyf.len() as u32);
let mut head = Vec::new();
be32(&mut head, 0x0001_0000);
be32(&mut head, 0x0001_0000);
be32(&mut head, 0);
be32(&mut head, 0x5F0F_3CF5);
be16(&mut head, 0);
be16(&mut head, 1000);
head.extend_from_slice(&[0; 16]);
for v in [0i16, 0, 600, 700] {
be16(&mut head, v as u16);
}
for v in [0u16, 8, 2, 1, 0] {
be16(&mut head, v);
}
let mut hhea = Vec::new();
be32(&mut hhea, 0x0001_0000);
for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut hhea, v as u16);
}
be16(&mut hhea, 3);
let mut maxp = Vec::new();
be32(&mut maxp, 0x0001_0000);
for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
be16(&mut maxp, v);
}
let mut hmtx = Vec::new();
for _ in 0..metrics {
be16(&mut hmtx, 600);
be16(&mut hmtx, 50);
}
// cmap: format 4, 'A'..'B' → 1..2.
let mut sub = Vec::new();
let segs: [(u16, u16, u16); 2] = [(0x41, 0x42, 1u16.wrapping_sub(0x41)), (0xFFFF, 0xFFFF, 1)];
be16(&mut sub, 4);
be16(&mut sub, (16 + segs.len() * 8) as u16);
be16(&mut sub, 0);
be16(&mut sub, (segs.len() * 2) as u16);
for v in [4u16, 1, 0] {
be16(&mut sub, v);
}
for s in segs {
be16(&mut sub, s.1);
}
be16(&mut sub, 0);
for s in segs {
be16(&mut sub, s.0);
}
for s in segs {
be16(&mut sub, s.2);
}
for _ in segs {
be16(&mut sub, 0);
}
let mut cmap = Vec::new();
for v in [0u16, 1, 3, 1] {
be16(&mut cmap, v);
}
be32(&mut cmap, 12);
cmap.extend_from_slice(&sub);
let mut os2 = vec![0u8; 78];
os2[8..10].copy_from_slice(&fs_type.to_be_bytes());
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
tables.sort_by_key(|t| *t.0);
let mut out = Vec::new();
be32(&mut out, 0x0001_0000);
for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] {
be16(&mut out, v);
}
let mut off = 12 + 16 * tables.len();
for (t, d) in &tables {
out.extend_from_slice(*t);
be32(&mut out, 0);
be32(&mut out, off as u32);
be32(&mut out, d.len() as u32);
off += d.len().div_ceil(4) * 4;
}
for (_, d) in &tables {
out.extend_from_slice(d);
while out.len() % 4 != 0 {
out.push(0);
}
}
out
sfnt::bytes(&sfnt::Sfnt {
// "A" is a triangle and "B" a square: one contour each.
glyphs: &[
sfnt::notdef(),
sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]),
sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]),
],
cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2
advance: 600,
lsb: 50,
metrics,
fs_type,
ink_box: [0, 0, 600, 700],
})
}
/// Register the test fonts once: an embeddable one, one with a restricted licence, and one
@@ -1,121 +0,0 @@
//! The registered applications (APPID) of a file are saved back, in DXF and in DWG, save after
//! save, also those no xdata names.
use cadcraft_doc::Drawing;
use cadcraft_io::{read, read_dxf, write, write_dxf};
/// The records of a DXF: each `(code, value)` from its `0` group on.
fn records(text: &str) -> Vec<Vec<(i32, String)>> {
let lines: Vec<&str> = text.lines().collect();
let mut out: Vec<Vec<(i32, String)>> = Vec::new();
for chunk in lines.chunks(2) {
let [code, value] = chunk else { break };
let Ok(c) = code.trim().parse::<i32>() else { continue };
let pair = (c, value.trim().to_string());
if c == 0 {
out.push(vec![pair]);
} else if let Some(r) = out.last_mut() {
r.push(pair);
}
}
out
}
/// The value of the record's first group `code`.
fn value(r: &[(i32, String)], code: i32) -> Option<&str> {
r.iter().find(|(c, _)| *c == code).map(|(_, v)| v.as_str())
}
/// A file whose APPID table has `Other_App` (handle 7A00), which no xdata names; with `xdata`,
/// a line's xdata names it as `OTHER_APP`.
fn source(xdata: bool) -> String {
let mut out = String::new();
let mut put = |c: i32, v: &str| out.push_str(&format!("{c:>3}\n{v}\n"));
for r in records(&write_dxf(&Drawing::new_metric())) {
for (c, v) in &r {
put(*c, v);
}
if xdata && r[0].1 == "SECTION" && value(&r, 2) == Some("ENTITIES") {
for (c, v) in [
(0, "LINE"),
(5, "7A01"),
(100, "AcDbEntity"),
(8, "0"),
(100, "AcDbLine"),
(10, "0"),
(20, "0"),
(30, "0"),
(11, "10"),
(21, "0"),
(31, "0"),
(1001, "OTHER_APP"),
(1000, "x"),
] {
put(c, v);
}
}
if r[0].1 == "TABLE" && value(&r, 2) == Some("APPID") {
let table = value(&r, 5).unwrap_or("0").to_string();
for (c, v) in [
(0, "APPID"),
(5, "7A00"),
(330, table.as_str()),
(100, "AcDbSymbolTableRecord"),
(100, "AcDbRegAppTableRecord"),
(2, "Other_App"),
(70, "0"),
] {
put(c, v);
}
}
}
out
}
/// How many APPID records of the DXF are named `Other_App`, in any case.
fn appids(text: &str) -> usize {
records(text).into_iter().filter(|r| r[0].1 == "APPID" && value(r, 2).is_some_and(|n| n.eq_ignore_ascii_case("Other_App"))).count()
}
#[test]
fn registered_applications_no_xdata_names_are_kept() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read_dxf(source(false).as_bytes()).expect("read");
for generation in 1..=2 {
let text = write_dxf(&d);
assert_eq!(appids(&text), 1, "DXF {generation}");
d = read_dxf(text.as_bytes()).expect("reread");
}
for generation in 1..=2 {
let dwg = write(&d, "kept.dwg").expect("DWG");
d = read(&dwg, "kept.dwg").expect("DWG read");
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
}
}
/// An application both registered and named by xdata, in another case, gets one record.
#[test]
fn a_registered_application_xdata_names_gets_one_record() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read_dxf(source(true).as_bytes()).expect("read");
for generation in 1..=2 {
let text = write_dxf(&d);
assert!(text.contains("OTHER_APP"), "DXF {generation}: the line's xdata is kept");
assert_eq!(appids(&text), 1, "DXF {generation}");
d = read_dxf(text.as_bytes()).expect("reread");
}
for generation in 1..=2 {
let dwg = write(&d, "kept.dwg").expect("DWG");
d = read(&dwg, "kept.dwg").expect("DWG read");
assert_eq!(appids(&write_dxf(&d)), 1, "DWG {generation}");
}
}
/// Registered applications alone are not kept objects: a file with nothing else to keep notes no
/// version, so the DWG writer reads its R2000 text as before rather than as the file's version.
#[test]
fn registered_applications_alone_note_no_version() {
let d = read_dxf(source(false).as_bytes()).expect("read");
assert!(d.foreign.appids.iter().any(|n| n == "Other_App"), "{:?}", d.foreign.appids);
assert_eq!(d.foreign.version, None);
}
+68
View File
@@ -3,6 +3,11 @@ use crate::*;
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
use cadcraft_geom::{PolyVertex, Vec3};
// The synthetic TrueType file both this suite and the PDF writer's build: the fonts layer's
// test-only helper, inlined rather than published or depended on.
#[path = "../../fonts/tests/support/sfnt.rs"]
mod sfnt;
fn sample() -> Drawing {
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))
@@ -277,6 +282,44 @@ fn system_font() -> Option<&'static str> {
["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find(|n| cadcraft_fonts::ttf::find(n).is_some())
}
// ---------- a fixture TrueType font: no font file, no installed font ----------
/// A closed ellipse round (500, 350), wound by `clockwise`: one contour of a glyph outline.
fn ring(rx: f64, ry: f64, points: usize, clockwise: bool) -> Vec<(i16, i16)> {
let dir = if clockwise { -1.0 } else { 1.0 };
(0..points)
.map(|i| {
(
(500.0 + rx * (dir * std::f64::consts::TAU * i as f64 / points as f64).cos()) as i16,
(350.0 + ry * (dir * std::f64::consts::TAU * i as f64 / points as f64).sin()) as i16,
)
})
.collect()
}
/// A TrueType font whose only glyph, "O", is a 128-point ring: the flattened outline a real font's
/// curve gives, at the same scale, with plenty of detail to simplify. It is built in code so the
/// level-of-detail test needs no installed font and no font file in the repository (#651).
fn fixture_font() -> &'static str {
const NAME: &str = "cadcraft-render-lod.ttf";
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| cadcraft_fonts::ttf::register(NAME, fixture_font_bytes()));
NAME
}
fn fixture_font_bytes() -> Vec<u8> {
sfnt::bytes(&sfnt::Sfnt {
// Glyph 1 is "O": a 128-point ring, its counter a second, oppositely wound contour.
glyphs: &[sfnt::notdef(), sfnt::glyph(&[ring(500.0, 350.0, 128, false), ring(250.0, 150.0, 128, true)])],
cmap: &[(0x4F, 0x4F, 1 - 0x4F)], // "O" → glyph 1
advance: 1000, // one em wide
lsb: 0,
metrics: 2, // hmtx matches the two metrics hhea declares
fs_type: 0, // any use
ink_box: [0, 0, 1000, 700], // the ring's box; the 700-unit cap height is the unit scale
})
}
#[test]
fn truetype_text_is_filled_or_outlined() {
let Some(font) = system_font() else { return };
@@ -298,6 +341,31 @@ fn truetype_text_is_filled_or_outlined() {
assert!(l.prims.len() >= 3, "O has two contours, H one");
}
// Regression test for #651: filled TrueType text was triangulated at full outline detail at every
// zoom, so a page of small text on screen produced millions of triangles and froze the canvas.
#[test]
fn small_filled_text_on_screen_is_simplified_but_plots_keep_full_detail() {
let d = text_doc(fixture_font(), "OOOO");
let tris = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Tris).map(|p| l.points(p).len() / 3).sum::<usize>();
let plot = build_plot(&d, &Space::Model, &Options::default());
let full = tris(&plot);
assert!(full > 100, "a plot keeps every point of the 128-point rings: {full} triangles");
// One pixel is a tenth of the cap height: the rings are simplified to a few points, the shapes
// stay.
let reduced = build(&d, &Space::Model, &screen(0.1, None));
assert!(tris(&reduced) < full / 2, "{} triangles at 10 px per cap height, {full} in a plot", tris(&reduced));
assert!(tris(&reduced) > 0 && reduced.bounds.width() > plot.bounds.width() * 0.9, "{:?} vs {:?}", reduced.bounds, plot.bounds);
// An em under two pixels is drawn as the ink's box: two triangles a glyph, same extent.
let tiny = build(&d, &Space::Model, &screen(2.0, None));
assert_eq!(tris(&tiny), 2 * 4, "one box per glyph");
assert!(
tiny.bounds.width() > plot.bounds.width() * 0.9 && tiny.bounds.height() > plot.bounds.height() * 0.9,
"{:?} vs {:?}",
tiny.bounds,
plot.bounds
);
}
#[test]
fn missing_font_falls_back_to_stroke() {
let d = text_doc("NoSuchFontAnywhere.ttf", "OH");
+28
View File
@@ -256,6 +256,34 @@ mod tests {
assert!(tris.iter().all(|p| (5.0e5..=5.0e5 + 2.0).contains(&p.x) && (-3.0e5..=-3.0e5 + 2.0).contains(&p.y)));
}
// Regression test for #651: the level of detail followed the pixel size, so a page of small
// filled text on screen kept a few points a glyph while a plot kept all of them.
#[test]
fn a_small_on_screen_pixel_simplifies_glyphs_and_a_plot_does_not() {
// Text of height 1 has a 700-unit cap height: one font unit is 1/700 of a drawing unit.
let xf = Mat3 { a: 1.0 / 700.0, b: 0.0, c: 0.0, d: 1.0 / 700.0, e: 0.0, f: 0.0 };
assert!(matches!(detail(xf, 0.0), Detail::Full), "a plot keeps every point");
assert!(matches!(detail(xf, 2.0), Detail::Box), "an em under two pixels is the ink's box");
assert!(matches!(detail(xf, 0.1), Detail::Reduced(band) if band >= 2), "10 px per cap height simplifies");
assert!(matches!(detail(xf, f64::NAN), Detail::Full), "a pixel size that is not a size keeps full detail");
}
#[test]
fn a_coarse_band_drops_the_points_of_a_flattened_curve() {
// A ring of 64 points, the outline a flattened curve gives.
let ring: Vec<Vec2> = (0..64u32)
.map(|i| {
let t = std::f64::consts::TAU * f64::from(i) / 64.0;
Vec2::new(500.0 * t.cos(), 350.0 * t.sin())
})
.collect();
let coarse = simplify(&ring, 8.0);
assert!(coarse.len() < ring.len() / 2, "{} of {} points kept at 8 font units", coarse.len(), ring.len());
assert!(coarse.len() >= 4, "a ring never collapses to a line: {}", coarse.len());
let fine = simplify(&ring, 0.01);
assert!(fine.len() >= ring.len(), "a fine band keeps every point: {} of {}", fine.len(), ring.len());
}
#[test]
fn hostile_placed_outline_never_panics() {
assert!(triangulate_placed(&[]).is_empty());
+3 -3
View File
@@ -133,8 +133,8 @@ pub fn entries(app: &CadApp) -> Vec<Vec<Entry>> {
}
/// The edit commands of the selected objects' type (when they are all of one type), with their
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit
/// and Generate Boundary for hatches, Polyline Edit, Spline Edit…
/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit,
/// Polyline Edit, Spline Edit…
fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
let Ok(d) = app.session.doc() else { return Vec::new() };
let sel = app.session.selection();
@@ -153,7 +153,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> {
}
v
}
EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)],
EntityKind::Hatch(_) => vec![("hatchedit", None)],
EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))],
EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))],
EntityKind::Dimension(_) => vec![("dimtedit", None)],
-1
View File
@@ -374,7 +374,6 @@
From Desde
From Template... Desde plantilla...
General General
Generate Boundary Generar contorno
Geometric Center Centro geométrico
Geometric Constraint Restricción geométrica
Geometric Constraints Restricciones geométricas
1 # CADCraft Spanish interface catalog — original translations.
374
375
376
377
378
379
-1
View File
@@ -296,7 +296,6 @@
Freeze/Thaw in the current viewport 在当前视口中冻结/解冻
From 自
General 常规
Generate Boundary 生成边界
Geometric Center 几何中心
Geometric Constraint 几何约束
Geometric Constraints 几何约束
1 # CADCraft Simplified Chinese interface catalog — original translations.
296
297
298
299
300
301
+1
View File
@@ -27,6 +27,7 @@ mod mtext_double_click;
mod named_viewports_dialog;
mod native_menu_text_keys;
mod native_windows;
mod offset_clicks;
mod options_dialog;
mod options_right_click;
mod page_setup_paper_units;
+83
View File
@@ -0,0 +1,83 @@
//! OFFSET on the canvas: the distance can be clicked, and picking the source is not moved by the
//! grid snap (#618).
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
use cadcraft_engine::geom::Vec2;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use serde_json::json;
fn harness() -> Harness<'static, CadApp> {
let mut d = Drawing::new_imperial();
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec2::new(0.0, 2.0).to3(0.0), b: Vec2::new(10.0, 2.0).to3(0.0) })).unwrap();
let mut session = Session::empty();
session.open_drawing(d, "Offset clicks", None);
session.execute("view.set", &json!({"center":[5,5],"height":20})).unwrap();
session.settings.osmode = 0;
session.settings.snapmode = true;
session.execute("setvar", &json!({"name":"SNAPUNIT","value":[5,5]})).unwrap();
session.settings.orthomode = false;
let mut app = CadApp::new(session, Services::default());
app.canvas.zoom_pending = false;
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(5);
h
}
fn click(h: &mut Harness<'_, CadApp>, world: Vec2) {
let pos: Pos2 = h.state().canvas.xf.unwrap().to_screen(world);
h.event(Event::PointerMoved(pos));
h.run_steps(2);
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
}
// Regression test for #618: OFFSET's distance could not be clicked, and with grid snap on a click
// meant to pick the source object was moved to the nearest grid point, missing the object.
#[test]
fn offset_takes_a_clicked_distance_and_picks_its_source_under_grid_snap() {
let mut h = harness();
h.state_mut().start("offset");
h.run_steps(2);
// Two clicks, snapped to the grid points (5, 5) and (10, 5): a distance of 5.
click(&mut h, Vec2::new(5.1, 4.9));
assert!(h.state().session.prompt_text().contains("second point"), "{}", h.state().session.prompt_text());
click(&mut h, Vec2::new(9.9, 5.1));
assert_eq!(h.state().session.doc().unwrap().header.f64("OFFSETDIST", -1.0), 5.0);
assert!(h.state().session.prompt_text().contains("Select object"), "{}", h.state().session.prompt_text());
// The source line is at y = 2, two units from the grid point (5, 0) the click would snap to.
click(&mut h, Vec2::new(7.0, 2.04));
let prompt = h.state().session.prompt_text();
assert!(prompt.contains("side to offset"), "the line was not picked: {prompt}");
// A side click above the line (snapped to (5, 5)) makes the copy 5 units up, at y = 7.
click(&mut h, Vec2::new(7.0, 7.0));
let lines: Vec<(f64, f64)> = h
.state()
.session
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(line) => Some((line.a.y, line.b.y)),
_ => None,
})
.collect();
assert_eq!(lines.len(), 2, "OFFSET added no line: {lines:?}");
assert!(lines.iter().any(|&(a, b)| (a - 7.0).abs() < 1e-9 && (b - 7.0).abs() < 1e-9), "no copy at y = 7: {lines:?}");
// OFFSET asks for the next object; Enter ends it.
assert!(h.state().session.prompt_text().contains("Select object to offset"), "{}", h.state().session.prompt_text());
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(h.state().session.prompt_text(), "Command:", "Enter ends OFFSET");
}