use std::collections::HashMap;
use std::rc::Rc;
use crate::aci;
use crate::geom::{BBox, Point3, Vec3};
use crate::geom_ops::{
EllipseArc, Transform, bulge_to_arc, ellipse_arc, extend_bbox, interpolate_fit_points,
nurbs_flatten,
};
use crate::model::{
Attachment, Block, Color, Document, Entity, EntityKind, HAlign, HatchEdge, Layer, VAlign,
Vertex,
};
pub const DEFAULT_WALK_DEPTH: u32 = 32;
pub const DEFAULT_MAX_WORK: u64 = 20_000_000;
const BLACK: (u8, u8, u8) = (0, 0, 0);
#[derive(Debug, Clone)]
pub struct WalkContext<'a> {
pub transform: Transform,
pub depth: u32,
pub inherited_layer: Option<&'a str>,
pub block_color: Option<(u8, u8, u8)>,
layer_colors: Option<Rc<HashMap<&'a str, Color>>>,
}
impl<'a> WalkContext<'a> {
pub fn root() -> Self {
Self {
transform: Transform::identity(),
depth: 0,
inherited_layer: None,
block_color: None,
layer_colors: None,
}
}
pub fn layer_name<'x>(&'x self, e: &'x Entity) -> &'x str {
match e.layer.as_deref() {
None | Some("0") => self.inherited_layer.unwrap_or("0"),
Some(name) => name,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BBoxOptions {
pub include_images: bool,
pub max_work: u64,
}
impl Default for BBoxOptions {
fn default() -> Self {
Self::new()
}
}
impl BBoxOptions {
pub const fn new() -> Self {
Self {
include_images: true,
max_work: DEFAULT_MAX_WORK,
}
}
#[must_use]
pub const fn with_include_images(mut self, include_images: bool) -> Self {
self.include_images = include_images;
self
}
#[must_use]
pub const fn with_max_work(mut self, max_work: u64) -> Self {
self.max_work = max_work;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WalkOptions {
pub max_depth: u32,
pub expand_inserts: bool,
pub max_work: u64,
}
impl Default for WalkOptions {
fn default() -> Self {
Self::new()
}
}
impl WalkOptions {
pub const fn new() -> Self {
Self {
max_depth: DEFAULT_WALK_DEPTH,
expand_inserts: true,
max_work: DEFAULT_MAX_WORK,
}
}
#[must_use]
pub const fn with_max_depth(mut self, max_depth: u32) -> Self {
self.max_depth = max_depth;
self
}
#[must_use]
pub const fn with_expand_inserts(mut self, expand_inserts: bool) -> Self {
self.expand_inserts = expand_inserts;
self
}
#[must_use]
pub const fn with_max_work(mut self, max_work: u64) -> Self {
self.max_work = max_work;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct WalkStats {
pub truncated: bool,
pub work: u64,
}
fn entity_cost(kind: &EntityKind) -> u64 {
let n = |len: usize| len as u64;
match kind {
EntityKind::Polyline { vertices, .. } => n(vertices.len()),
EntityKind::Spline {
control_points,
fit_points,
..
} => n(control_points.len().max(fit_points.len()))
.saturating_mul(SPLINE_SAMPLES as u64)
.min(100_000),
EntityKind::Text { value, .. } => n(value.len()),
EntityKind::MText { value, plain, .. } => n(value.len()) + n(plain.len()),
EntityKind::Hatch { loops, .. } => loops
.iter()
.flat_map(|l| l.edges.iter())
.map(|e| match e {
HatchEdge::Polyline { vertices, .. } => 1 + n(vertices.len()),
HatchEdge::Spline { control_points, .. } => {
1 + n(control_points.len())
.saturating_mul(SPLINE_SAMPLES as u64)
.min(100_000)
}
_ => 4,
})
.fold(0u64, u64::saturating_add),
EntityKind::Dimension { points, .. } | EntityKind::Face { points, .. } => n(points.len()),
EntityKind::Polygon {
exterior,
interiors,
} => interiors.iter().fold(n(exterior.len()), |sum, ring| {
sum.saturating_add(n(ring.len()))
}),
EntityKind::Leader { vertices, .. } => n(vertices.len()),
EntityKind::Mesh { vertices, faces } => {
n(vertices.len())
+ faces
.iter()
.map(|f| n(f.len()) + 1)
.fold(0u64, u64::saturating_add)
}
_ => 0,
}
}
struct Walker<'a, F> {
blocks: HashMap<&'a str, &'a Block>,
layers: HashMap<&'a str, &'a Layer>,
colors: Rc<HashMap<&'a str, Color>>,
opts: WalkOptions,
include_hidden_layers: bool,
work: u64,
spent: u64,
truncated: bool,
stack: Vec<&'a str>,
f: F,
}
impl<'a, F: FnMut(&'a Entity, &WalkContext<'a>) -> bool> Walker<'a, F> {
fn layer_hidden(&self, name: &str) -> bool {
!self.include_hidden_layers
&& self
.layers
.get(name)
.is_some_and(|l| !l.visible || l.frozen)
}
fn color_of(&self, e: &Entity, ctx: &WalkContext<'a>) -> (u8, u8, u8) {
let name = ctx.layer_name(e);
resolve_color(e.color, || self.colors.get(name).copied(), ctx.block_color)
}
fn charge(&mut self, cost: u64) -> bool {
if self.truncated {
return false;
}
if cost > self.work {
self.work = 0;
self.truncated = true;
return false;
}
self.work -= cost;
self.spent += cost;
true
}
fn emit(&mut self, e: &'a Entity, ctx: &WalkContext<'a>) {
if !(self.f)(e, ctx) {
self.truncated = true;
}
}
fn visit_list(&mut self, list: &'a [Entity], ctx: &WalkContext<'a>) {
for e in list {
if self.truncated {
return;
}
self.visit(e, ctx);
}
}
fn visit(&mut self, e: &'a Entity, ctx: &WalkContext<'a>) {
if !self.charge(1 + entity_cost(&e.kind)) {
return;
}
let layer = ctx.layer_name(e);
if !e.visible || self.layer_hidden(layer) {
return;
}
match &e.kind {
EntityKind::Insert {
block,
position,
scale,
rotation,
normal,
columns,
rows,
column_spacing,
row_spacing,
} if self.opts.expand_inserts => {
let Some(def) = self.blocks.get(block.as_str()).copied() else {
self.emit(e, ctx);
return;
};
if ctx.depth >= self.opts.max_depth || self.stack.contains(&def.name.as_str()) {
self.emit(e, ctx);
return;
}
let child_layer: Option<&'a str> = match e.layer.as_deref() {
None | Some("0") => ctx.inherited_layer,
Some(l) => Some(l),
};
let block_color = Some(self.color_of(e, ctx));
self.stack.push(def.name.as_str());
'outer: for r in 0..(*rows).max(1) {
for c in 0..(*columns).max(1) {
if !self.charge(1) {
break 'outer;
}
let offset = Vec3::new(
f64::from(c) * column_spacing,
f64::from(r) * row_spacing,
0.0,
);
let local = Transform::from_insert_offset(
*position,
*scale,
*rotation,
*normal,
def.base_point,
offset,
);
let child = WalkContext {
transform: ctx.transform.compose(&local),
depth: ctx.depth + 1,
inherited_layer: child_layer,
block_color,
layer_colors: ctx.layer_colors.clone(),
};
self.visit_list(&def.entities, &child);
}
}
self.stack.pop();
}
EntityKind::Dimension {
block: Some(name), ..
} if self.opts.expand_inserts => match self.blocks.get(name.as_str()).copied() {
Some(def)
if ctx.depth < self.opts.max_depth
&& !self.stack.contains(&def.name.as_str()) =>
{
let child_layer: Option<&'a str> = match e.layer.as_deref() {
None | Some("0") => ctx.inherited_layer,
Some(l) => Some(l),
};
let child = WalkContext {
transform: ctx.transform,
depth: ctx.depth + 1,
inherited_layer: child_layer,
block_color: Some(self.color_of(e, ctx)),
layer_colors: ctx.layer_colors.clone(),
};
self.stack.push(def.name.as_str());
self.visit_list(&def.entities, &child);
self.stack.pop();
}
_ => self.emit(e, ctx),
},
EntityKind::Group { children, .. } => {
if ctx.depth < self.opts.max_depth {
let child = WalkContext {
depth: ctx.depth + 1,
..ctx.clone()
};
self.visit_list(children, &child);
}
}
_ => self.emit(e, ctx),
}
}
}
impl Document {
pub fn walk<'a, F>(&'a self, model_index: usize, max_depth: u32, mut f: F)
where
F: FnMut(&'a Entity, &WalkContext<'a>),
{
let opts = WalkOptions {
max_depth,
..WalkOptions::default()
};
self.walk_while(model_index, &opts, |e, c| {
f(e, c);
true
});
}
pub fn walk_with<'a, F>(
&'a self,
model_index: usize,
options: &WalkOptions,
mut f: F,
) -> WalkStats
where
F: FnMut(&'a Entity, &WalkContext<'a>),
{
self.walk_while(model_index, options, |e, c| {
f(e, c);
true
})
}
pub fn walk_while<'a, F>(&'a self, model_index: usize, options: &WalkOptions, f: F) -> WalkStats
where
F: FnMut(&'a Entity, &WalkContext<'a>) -> bool,
{
self.walk_while_internal(model_index, options, false, f)
}
pub fn walk_all_layers_while<'a, F>(
&'a self,
model_index: usize,
options: &WalkOptions,
f: F,
) -> WalkStats
where
F: FnMut(&'a Entity, &WalkContext<'a>) -> bool,
{
self.walk_while_internal(model_index, options, true, f)
}
fn walk_while_internal<'a, F>(
&'a self,
model_index: usize,
options: &WalkOptions,
include_hidden_layers: bool,
f: F,
) -> WalkStats
where
F: FnMut(&'a Entity, &WalkContext<'a>) -> bool,
{
let Some(model) = self.models.get(model_index) else {
return WalkStats::default();
};
let mut blocks = HashMap::new();
for b in &self.blocks {
blocks.entry(b.name.as_str()).or_insert(b);
}
let mut layers = HashMap::new();
for l in &self.layers {
layers.entry(l.name.as_str()).or_insert(l);
}
let mut colors = HashMap::new();
for l in &self.layers {
colors.entry(l.name.as_str()).or_insert(l.color);
}
let colors = Rc::new(colors);
let mut w = Walker {
blocks,
layers,
colors: Rc::clone(&colors),
opts: *options,
include_hidden_layers,
work: options.max_work,
spent: 0,
truncated: false,
stack: Vec::new(),
f,
};
let root = WalkContext {
layer_colors: Some(colors),
..WalkContext::root()
};
w.visit_list(&model.entities, &root);
WalkStats {
truncated: w.truncated,
work: w.spent,
}
}
pub fn bbox(&self, model_index: usize) -> Option<BBox> {
self.bbox_with(model_index, &BBoxOptions::default())
}
pub fn bbox_with(&self, model_index: usize, options: &BBoxOptions) -> Option<BBox> {
self.bbox_internal(model_index, options, false)
}
pub fn bbox_all_layers_with(&self, model_index: usize, options: &BBoxOptions) -> Option<BBox> {
self.bbox_internal(model_index, options, true)
}
fn bbox_internal(
&self,
model_index: usize,
options: &BBoxOptions,
include_hidden_layers: bool,
) -> Option<BBox> {
let mut bb = None;
let walk = WalkOptions {
max_work: options.max_work,
..WalkOptions::default()
};
self.walk_while_internal(model_index, &walk, include_hidden_layers, |e, ctx| {
if !options.include_images && matches!(e.kind, EntityKind::Image { .. }) {
return true;
}
entity_extents(e, &ctx.transform, &mut bb);
true
});
bb
}
}
fn display_rgb(c: Color) -> Option<(u8, u8, u8)> {
match c {
Color::Rgb { r, g, b } => Some((r, g, b)),
Color::Aci { index: 0 } | Color::ByLayer | Color::ByBlock => None,
Color::Aci { index: 7 } => Some(BLACK),
Color::Aci { index } => Some(aci::to_rgb(index)),
}
}
fn resolve_color(
c: Color,
layer_color: impl FnOnce() -> Option<Color>,
block: Option<(u8, u8, u8)>,
) -> (u8, u8, u8) {
if let Some(rgb) = display_rgb(c) {
return rgb;
}
match c {
Color::ByLayer => layer_color().and_then(display_rgb).unwrap_or(BLACK),
_ => block.unwrap_or(BLACK),
}
}
impl Entity {
pub fn resolved_color(&self, doc: &Document) -> (u8, u8, u8) {
self.resolved_color_in(doc, &WalkContext::root())
}
pub fn resolved_color_in(&self, doc: &Document, ctx: &WalkContext<'_>) -> (u8, u8, u8) {
let name = ctx.layer_name(self);
resolve_color(
self.color,
|| match &ctx.layer_colors {
Some(map) => map.get(name).copied(),
None => doc.layers.iter().find(|l| l.name == name).map(|l| l.color),
},
ctx.block_color,
)
}
pub fn bbox(&self) -> Option<BBox> {
entity_bbox(self, &Transform::identity())
}
pub fn bbox_in(&self, transform: &Transform) -> Option<BBox> {
entity_bbox(self, transform)
}
}
impl EntityKind {
pub fn type_name(&self) -> &'static str {
match self {
Self::Point { .. } => "point",
Self::Line { .. } => "line",
Self::Polyline { .. } => "polyline",
Self::Circle { .. } => "circle",
Self::Arc { .. } => "arc",
Self::Ellipse { .. } => "ellipse",
Self::Spline { .. } => "spline",
Self::Text { .. } => "text",
Self::MText { .. } => "mtext",
Self::Insert { .. } => "insert",
Self::Hatch { .. } => "hatch",
Self::Dimension { .. } => "dimension",
Self::Face { .. } => "face",
Self::Polygon { .. } => "polygon",
Self::Leader { .. } => "leader",
Self::Image { .. } => "image",
Self::Viewport { .. } => "viewport",
Self::Mesh { .. } => "mesh",
Self::Group { .. } => "group",
Self::Unknown { .. } => "unknown",
}
}
}
pub(crate) fn circle_arc(
center: Point3,
radius: f64,
start: f64,
end: f64,
normal: Vec3,
tf: &Transform,
) -> EllipseArc {
EllipseArc::circle(Point3::default(), radius, start, end)
.transformed(&tf.compose(&Transform::plane(center, normal)))
}
pub(crate) fn full_ellipse_arc(
center: Point3,
major: Vec3,
ratio: f64,
normal: Vec3,
start: f64,
end: f64,
tf: &Transform,
) -> EllipseArc {
ellipse_arc(center, major, ratio, normal, start, end).transformed(tf)
}
pub(crate) fn segment_arc(
a: &Vertex,
b: &Vertex,
normal: Vec3,
tf: &Transform,
) -> Option<EllipseArc> {
let plane = Transform::plane(a.position, normal);
let d = a.position.vector_to(b.position);
let local_b = (d.dot(plane.x), d.dot(plane.y));
let arc = bulge_to_arc((0.0, 0.0), local_b, a.bulge)?;
let e = EllipseArc {
center: Point3::new(arc.center.0, arc.center.1, 0.0),
u: Vec3::new(arc.radius, 0.0, 0.0),
v: Vec3::new(0.0, arc.radius, 0.0),
t0: arc.start_angle,
t1: arc.start_angle + arc.sweep,
};
Some(e.transformed(&tf.compose(&plane)))
}
pub(crate) const SPLINE_SAMPLES: usize = 16;
pub(crate) fn spline_points(
degree: u32,
knots: &[f64],
control: &[Point3],
weights: &[f64],
fit: &[Point3],
closed: bool,
tf: &Transform,
) -> Vec<Point3> {
let pts = if control.len() >= 2 {
nurbs_flatten(degree, knots, control, weights, SPLINE_SAMPLES)
} else if fit.len() >= 2 {
if let Some((deg, iknots, ictrl)) = interpolate_fit_points(fit, closed) {
nurbs_flatten(deg, &iknots, &ictrl, &[], SPLINE_SAMPLES)
} else {
fit.to_vec()
}
} else {
control.to_vec()
};
pts.into_iter().map(|p| tf.apply_point(p)).collect()
}
fn text_box(
chars: usize,
height: f64,
width_factor: f64,
halign: HAlign,
valign: VAlign,
) -> ((f64, f64), (f64, f64)) {
let wf = if width_factor.is_finite() && width_factor > 0.0 {
width_factor
} else {
1.0
};
let w = 0.6 * height * wf * chars.max(1) as f64;
let valign = if matches!(halign, HAlign::Aligned | HAlign::Fit) {
VAlign::Baseline
} else {
valign
};
let x = match halign {
HAlign::Left | HAlign::Aligned | HAlign::Fit => (0.0, w),
HAlign::Right => (-w, 0.0),
_ => (-w / 2.0, w / 2.0),
};
let y = match valign {
VAlign::Baseline | VAlign::Bottom => (0.0, height),
VAlign::Middle => (-height / 2.0, height / 2.0),
VAlign::Top => (-height, 0.0),
};
(x, y)
}
fn extend_box(
bb: &mut Option<BBox>,
origin: Point3,
rotation: f64,
x: (f64, f64),
y: (f64, f64),
tf: &Transform,
) {
let (s, c) = rotation.sin_cos();
for px in [x.0, x.1] {
for py in [y.0, y.1] {
let p = Point3::new(
origin.x + px * c - py * s,
origin.y + px * s + py * c,
origin.z,
);
extend_bbox(bb, tf.apply_point(p));
}
}
}
pub(crate) fn mtext_text_lines(value: &str, plain: &str) -> Vec<String> {
if !plain.is_empty() {
plain
.split('\n')
.map(|s| s.trim_end_matches('\r').to_owned())
.collect()
} else {
value.split("\\P").map(str::to_owned).collect()
}
}
pub(crate) fn attachment_anchor(a: Attachment) -> (i8, i8) {
match a {
Attachment::TopLeft => (-1, -1),
Attachment::TopCenter => (0, -1),
Attachment::TopRight => (1, -1),
Attachment::MiddleLeft => (-1, 0),
Attachment::MiddleCenter => (0, 0),
Attachment::MiddleRight => (1, 0),
Attachment::BottomLeft => (-1, 1),
Attachment::BottomCenter => (0, 1),
Attachment::BottomRight => (1, 1),
}
}
pub(crate) fn mtext_line_height(height: f64, line_spacing: f64) -> f64 {
let f = if line_spacing.is_finite() && line_spacing > 0.0 {
line_spacing
} else {
1.0
};
height * f * (5.0 / 3.0)
}
fn extend_hatch_edge(bb: &mut Option<BBox>, edge: &HatchEdge, normal: Vec3, tf: &Transform) {
match edge {
HatchEdge::Line { start, end } => {
extend_bbox(bb, tf.apply_point(*start));
extend_bbox(bb, tf.apply_point(*end));
}
HatchEdge::Arc {
center,
radius,
start_angle,
end_angle,
ccw,
} => {
let (s, en) = if *ccw {
(*start_angle, *end_angle)
} else {
(*end_angle, *start_angle)
};
circle_arc(*center, *radius, s, en, normal, tf).extend_bbox(bb);
}
HatchEdge::Ellipse {
center,
major_axis,
ratio,
start_param,
end_param,
ccw,
} => {
let (s, en) = if *ccw {
(*start_param, *end_param)
} else {
(*end_param, *start_param)
};
full_ellipse_arc(*center, *major_axis, *ratio, normal, s, en, tf).extend_bbox(bb);
}
HatchEdge::Spline {
degree,
knots,
control_points,
weights,
} => {
for p in spline_points(*degree, knots, control_points, weights, &[], false, tf) {
extend_bbox(bb, p);
}
}
HatchEdge::Polyline { vertices, closed } => {
extend_polyline(bb, vertices, *closed, normal, tf)
}
}
}
fn extend_polyline(
bb: &mut Option<BBox>,
vertices: &[Vertex],
closed: bool,
normal: Vec3,
tf: &Transform,
) {
for v in vertices {
extend_bbox(bb, tf.apply_point(v.position));
}
let n = vertices.len();
let segs = if closed { n } else { n.saturating_sub(1) };
for i in 0..segs {
if let (Some(a), Some(b)) = (vertices.get(i), vertices.get((i + 1) % n.max(1)))
&& let Some(arc) = segment_arc(a, b, normal, tf)
{
arc.extend_bbox(bb);
}
}
}
fn entity_extents(e: &Entity, tf: &Transform, bb: &mut Option<BBox>) {
match &e.kind {
EntityKind::Point { position } => extend_bbox(bb, tf.apply_point(*position)),
EntityKind::Line { start, end } => {
extend_bbox(bb, tf.apply_point(*start));
extend_bbox(bb, tf.apply_point(*end));
}
EntityKind::Polyline {
vertices,
closed,
normal,
} => extend_polyline(bb, vertices, *closed, *normal, tf),
EntityKind::Circle {
center,
radius,
normal,
} => {
circle_arc(*center, *radius, 0.0, 0.0, *normal, tf).extend_bbox(bb);
}
EntityKind::Arc {
center,
radius,
start_angle,
end_angle,
normal,
} => {
circle_arc(*center, *radius, *start_angle, *end_angle, *normal, tf).extend_bbox(bb);
}
EntityKind::Ellipse {
center,
major_axis,
ratio,
start_param,
end_param,
normal,
} => {
full_ellipse_arc(
*center,
*major_axis,
*ratio,
*normal,
*start_param,
*end_param,
tf,
)
.extend_bbox(bb);
}
EntityKind::Spline {
degree,
knots,
control_points,
weights,
fit_points,
closed,
} => {
for p in spline_points(
*degree,
knots,
control_points,
weights,
fit_points,
*closed,
tf,
) {
extend_bbox(bb, p);
}
}
EntityKind::Text {
position,
end_point: Some(end),
height,
normal,
..
} => {
let dir = position.vector_to(*end);
let up = normal
.cross(dir)
.normalized()
.unwrap_or(Vec3::new(0.0, 1.0, 0.0))
.scaled(*height);
for p in [*position, *end] {
extend_bbox(bb, tf.apply_point(p));
extend_bbox(bb, tf.apply_point(p.translated(up)));
}
}
EntityKind::Text {
position,
height,
rotation,
width_factor,
value,
halign,
valign,
normal,
..
} => {
let (x, y) = text_box(
value.chars().count(),
*height,
*width_factor,
*halign,
*valign,
);
extend_box(
bb,
Point3::default(),
*rotation,
x,
y,
&tf.compose(&Transform::plane(*position, *normal)),
);
}
EntityKind::MText {
position,
height,
width,
rotation,
value,
plain,
attachment,
line_spacing,
normal,
..
} => {
let lines = mtext_text_lines(value, plain);
let widest = lines.iter().map(|l| l.chars().count()).max().unwrap_or(1);
let w = if *width > 0.0 && width.is_finite() {
*width
} else {
0.6 * height * widest as f64
};
let h = mtext_line_height(*height, *line_spacing) * lines.len().max(1) as f64;
let (ha, va) = attachment_anchor(*attachment);
let x = match ha {
-1 => (0.0, w),
0 => (-w / 2.0, w / 2.0),
_ => (-w, 0.0),
};
let y = match va {
-1 => (-h, 0.0),
0 => (-h / 2.0, h / 2.0),
_ => (0.0, h),
};
extend_box(
bb,
Point3::default(),
*rotation,
x,
y,
&tf.compose(&Transform::plane(*position, *normal)),
);
}
EntityKind::Insert { position, .. } => {
extend_bbox(bb, tf.apply_point(*position));
}
EntityKind::Hatch { loops, normal, .. } => {
for l in loops {
for edge in &l.edges {
extend_hatch_edge(bb, edge, *normal, tf);
}
}
}
EntityKind::Dimension {
points,
text_position,
..
} => {
for p in points.iter().chain(text_position.iter()) {
extend_bbox(bb, tf.apply_point(*p));
}
}
EntityKind::Face { points, .. } => {
for p in points {
extend_bbox(bb, tf.apply_point(*p));
}
}
EntityKind::Polygon {
exterior,
interiors,
} => {
for p in exterior.iter().chain(interiors.iter().flatten()) {
extend_bbox(bb, tf.apply_point(*p));
}
}
EntityKind::Leader { vertices, .. } => {
for p in vertices {
extend_bbox(bb, tf.apply_point(*p));
}
}
EntityKind::Image {
position,
u_vector,
v_vector,
..
} => {
for (a, b) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {
let p = position.translated(u_vector.scaled(a).plus(v_vector.scaled(b)));
extend_bbox(bb, tf.apply_point(p));
}
}
EntityKind::Mesh { vertices, .. } => {
for p in vertices {
extend_bbox(bb, tf.apply_point(*p));
}
}
EntityKind::Viewport { .. } | EntityKind::Group { .. } | EntityKind::Unknown { .. } => {}
}
}
pub fn entity_bbox(entity: &Entity, transform: &Transform) -> Option<BBox> {
let mut bb = None;
entity_extents(entity, transform, &mut bb);
bb
}
fn seg_dist_xy(px: f64, py: f64, a: Point3, b: Point3) -> f64 {
let dx = b.x - a.x;
let dy = b.y - a.y;
let len_sq = dx * dx + dy * dy;
if !(len_sq.is_finite() && len_sq > 1e-24) {
return (px - a.x).hypot(py - a.y);
}
let t = (((px - a.x) * dx + (py - a.y) * dy) / len_sq).clamp(0.0, 1.0);
(px - (a.x + t * dx)).hypot(py - (a.y + t * dy))
}
fn arc_dist_xy(px: f64, py: f64, arc: &EllipseArc) -> f64 {
let radius = arc.u.x.hypot(arc.u.y);
let other_radius = arc.v.x.hypot(arc.v.y);
let dot = arc.u.x * arc.v.x + arc.u.y * arc.v.y;
if radius.is_finite()
&& radius > 0.0
&& (radius - other_radius).abs() <= radius * 1e-12
&& dot.abs() <= radius * other_radius * 1e-12
{
let dx = px - arc.center.x;
let dy = py - arc.center.y;
let t = (dx * arc.v.x + dy * arc.v.y).atan2(dx * arc.u.x + dy * arc.u.y);
let sweep = arc.sweep();
let travel = if sweep >= 0.0 { t - arc.t0 } else { arc.t0 - t };
if sweep.abs() >= std::f64::consts::TAU - 1e-12
|| travel.rem_euclid(std::f64::consts::TAU) <= sweep.abs()
{
return (dx.hypot(dy) - radius).abs();
}
let a = arc.point(arc.t0);
let b = arc.point(arc.t1);
return (px - a.x).hypot(py - a.y).min((px - b.x).hypot(py - b.y));
}
let steps = ((arc.sweep().abs() / 0.1).ceil() as usize).clamp(16, 256);
let mut best = f64::INFINITY;
let mut prev = arc.point(arc.t0);
for i in 1..=steps {
let t = arc.t0 + (arc.t1 - arc.t0) * (i as f64) / (steps as f64);
let cur = arc.point(t);
best = best.min(seg_dist_xy(px, py, prev, cur));
prev = cur;
}
best
}
fn ring_contains_xy(px: f64, py: f64, ring: &[Point3], tf: &Transform) -> bool {
let n = ring.len();
if n < 3 {
return false;
}
let mut inside = false;
for i in 0..n {
let (Some(ra), Some(rb)) = (ring.get(i), ring.get((i + 1) % n)) else {
continue;
};
let a = tf.apply_point(*ra);
let b = tf.apply_point(*rb);
if (a.y > py) != (b.y > py) {
let x_cross = a.x + (py - a.y) * (b.x - a.x) / (b.y - a.y);
if px < x_cross {
inside = !inside;
}
}
}
inside
}
fn ring_edge_dist_xy(px: f64, py: f64, ring: &[Point3], closed: bool, tf: &Transform) -> f64 {
let n = ring.len();
if n == 0 {
return f64::INFINITY;
}
if n == 1 {
let p = ring
.first()
.map_or(Point3::default(), |pt| tf.apply_point(*pt));
return (px - p.x).hypot(py - p.y);
}
let segs = if closed { n } else { n - 1 };
let mut best = f64::INFINITY;
for i in 0..segs {
if let (Some(ra), Some(rb)) = (ring.get(i), ring.get((i + 1) % n)) {
best = best.min(seg_dist_xy(
px,
py,
tf.apply_point(*ra),
tf.apply_point(*rb),
));
}
}
best
}
pub fn entity_distance_xy(
entity: &Entity,
transform: &Transform,
point: (f64, f64),
) -> Option<f64> {
let (px, py) = point;
if !(px.is_finite() && py.is_finite()) {
return None;
}
match &entity.kind {
EntityKind::Point { position } => {
let p = transform.apply_point(*position);
Some((px - p.x).hypot(py - p.y))
}
EntityKind::Line { start, end } => Some(seg_dist_xy(
px,
py,
transform.apply_point(*start),
transform.apply_point(*end),
)),
EntityKind::Polyline {
vertices,
closed,
normal,
} => {
let n = vertices.len();
if n == 0 {
return None;
}
if n == 1 {
let p = vertices
.first()
.map_or(Point3::default(), |v| transform.apply_point(v.position));
return Some((px - p.x).hypot(py - p.y));
}
let segs = if *closed { n } else { n - 1 };
let mut best = f64::INFINITY;
for i in 0..segs {
let (Some(a), Some(b)) = (vertices.get(i), vertices.get((i + 1) % n)) else {
continue;
};
let d = if let Some(arc) = segment_arc(a, b, *normal, transform) {
arc_dist_xy(px, py, &arc)
} else {
seg_dist_xy(
px,
py,
transform.apply_point(a.position),
transform.apply_point(b.position),
)
};
best = best.min(d);
}
best.is_finite().then_some(best)
}
EntityKind::Circle {
center,
radius,
normal,
} => {
let arc = circle_arc(*center, *radius, 0.0, 0.0, *normal, transform);
Some(arc_dist_xy(px, py, &arc))
}
EntityKind::Arc {
center,
radius,
start_angle,
end_angle,
normal,
} => {
let arc = circle_arc(
*center,
*radius,
*start_angle,
*end_angle,
*normal,
transform,
);
Some(arc_dist_xy(px, py, &arc))
}
EntityKind::Ellipse {
center,
major_axis,
ratio,
start_param,
end_param,
normal,
} => {
let arc = full_ellipse_arc(
*center,
*major_axis,
*ratio,
*normal,
*start_param,
*end_param,
transform,
);
Some(arc_dist_xy(px, py, &arc))
}
EntityKind::Spline {
degree,
knots,
control_points,
weights,
fit_points,
closed,
} => {
let pts = spline_points(
*degree,
knots,
control_points,
weights,
fit_points,
*closed,
transform,
);
let d = ring_edge_dist_xy(px, py, &pts, *closed, &Transform::identity());
d.is_finite().then_some(d)
}
EntityKind::Leader { vertices, .. } => {
let d = ring_edge_dist_xy(px, py, vertices, false, transform);
d.is_finite().then_some(d)
}
EntityKind::Face { points, filled } => {
if *filled && ring_contains_xy(px, py, points, transform) {
return Some(0.0);
}
let d = ring_edge_dist_xy(px, py, points, true, transform);
d.is_finite().then_some(d)
}
EntityKind::Polygon {
exterior,
interiors,
} => {
let in_ext = ring_contains_xy(px, py, exterior, transform);
let in_hole = interiors
.iter()
.any(|hole| ring_contains_xy(px, py, hole, transform));
if in_ext && !in_hole {
return Some(0.0);
}
let mut best = ring_edge_dist_xy(px, py, exterior, true, transform);
for hole in interiors {
best = best.min(ring_edge_dist_xy(px, py, hole, true, transform));
}
best.is_finite().then_some(best)
}
_ => {
let bb = entity_bbox(entity, transform)?;
let dx = if px < bb.min.x {
bb.min.x - px
} else if px > bb.max.x {
px - bb.max.x
} else {
0.0
};
let dy = if py < bb.min.y {
bb.min.y - py
} else if py > bb.max.y {
py - bb.max.y
} else {
0.0
};
Some(dx.hypot(dy))
}
}
}
#[cfg(test)]
mod tests {
use std::f64::consts::PI;
use super::*;
use crate::model::{Model, Units};
fn line(x0: f64, y0: f64, x1: f64, y1: f64) -> Entity {
Entity::new(EntityKind::Line {
start: Point3::xy(x0, y0),
end: Point3::xy(x1, y1),
})
}
fn insert(block: &str, x: f64, y: f64) -> Entity {
Entity::new(EntityKind::Insert {
block: block.to_owned(),
position: Point3::xy(x, y),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
normal: Vec3::Z,
columns: 1,
rows: 1,
column_spacing: 0.0,
row_spacing: 0.0,
})
}
fn doc_with(models: Vec<Entity>, blocks: Vec<Block>) -> Document {
Document {
units: Units::default(),
blocks,
models: vec![Model {
name: "Model".into(),
entities: models,
..Model::default()
}],
..Document::default()
}
}
fn block(name: &str, entities: Vec<Entity>) -> Block {
Block {
name: name.to_owned(),
entities,
..Block::default()
}
}
fn collect(doc: &Document, depth: u32) -> Vec<(Point3, u32)> {
let mut out = Vec::new();
doc.walk(0, depth, |e, ctx| {
if let EntityKind::Line { start, .. } = &e.kind {
out.push((ctx.transform.apply_point(*start), ctx.depth));
}
});
out
}
#[test]
fn walk_expands_nested_inserts() {
let inner = block("inner", vec![line(0.0, 0.0, 1.0, 0.0)]);
let outer = block("outer", vec![insert("inner", 5.0, 0.0)]);
let doc = doc_with(vec![insert("outer", 0.0, 10.0)], vec![inner, outer]);
let hits = collect(&doc, 8);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].0, Point3::new(5.0, 10.0, 0.0));
assert_eq!(hits[0].1, 2);
}
#[test]
fn walk_depth_limit_reports_insert() {
let inner = block("inner", vec![line(0.0, 0.0, 1.0, 0.0)]);
let outer = block("outer", vec![insert("inner", 5.0, 0.0)]);
let doc = doc_with(vec![insert("outer", 0.0, 0.0)], vec![inner, outer]);
let mut inserts = 0;
let mut lines = 0;
doc.walk(0, 1, |e, _| match e.kind {
EntityKind::Insert { .. } => inserts += 1,
EntityKind::Line { .. } => lines += 1,
_ => {}
});
assert_eq!((inserts, lines), (1, 0));
}
#[test]
fn walk_survives_cycles() {
let a = block("a", vec![line(0.0, 0.0, 1.0, 1.0), insert("b", 1.0, 0.0)]);
let b = block("b", vec![insert("a", 1.0, 0.0)]);
let selfref = block("s", vec![insert("s", 0.0, 0.0)]);
let doc = doc_with(
vec![insert("a", 0.0, 0.0), insert("s", 0.0, 0.0)],
vec![a, b, selfref],
);
let mut n = 0;
doc.walk(0, 64, |_, _| n += 1);
assert_eq!(n, 3);
assert!(doc.bbox(0).is_some());
}
#[test]
fn walk_arrays_and_scale() {
let blk = block("b", vec![line(0.0, 0.0, 1.0, 0.0)]);
let mut ins = insert("b", 0.0, 0.0);
ins.kind = EntityKind::Insert {
block: "b".into(),
position: Point3::xy(0.0, 0.0),
scale: Vec3::new(2.0, 2.0, 1.0),
rotation: PI / 2.0,
normal: Vec3::Z,
columns: 2,
rows: 2,
column_spacing: 10.0,
row_spacing: 20.0,
};
let doc = doc_with(vec![ins], vec![blk]);
let mut starts = Vec::new();
doc.walk(0, 8, |e, ctx| {
if let EntityKind::Line { start, .. } = &e.kind {
starts.push(ctx.transform.apply_point(*start));
}
});
assert_eq!(starts.len(), 4);
let has = |x: f64, y: f64| {
starts
.iter()
.any(|p| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9)
};
assert!(has(0.0, 0.0) && has(0.0, 10.0) && has(-20.0, 0.0) && has(-20.0, 10.0));
}
#[test]
fn walk_huge_array_is_bounded() {
let blk = block("b", vec![line(0.0, 0.0, 1.0, 0.0)]);
let mut ins = insert("b", 0.0, 0.0);
if let EntityKind::Insert { columns, rows, .. } = &mut ins.kind {
*columns = u32::MAX;
*rows = u32::MAX;
}
let doc = doc_with(vec![ins], vec![blk]);
let mut n = 0u64;
doc.walk(0, 8, |_, _| n += 1);
assert!(n <= DEFAULT_MAX_WORK);
}
#[test]
fn walk_work_budget_counts_geometry_and_reports_truncation() {
let big = Entity::new(EntityKind::Polyline {
vertices: vec![Vertex::default(); 1000],
closed: false,
normal: Vec3::Z,
});
let doc = doc_with(vec![big.clone(), big.clone(), big], vec![]);
let mut n = 0;
let stats = doc.walk_with(
0,
&WalkOptions {
max_work: 2_500,
..WalkOptions::default()
},
|_, _| n += 1,
);
assert_eq!(n, 2);
assert!(stats.truncated);
let stats = doc.walk_with(0, &WalkOptions::default(), |_, _| n += 1);
assert!(!stats.truncated && stats.work == 3 * 1001);
let mut seen = 0;
let stats = doc.walk_while(0, &WalkOptions::default(), |_, _| {
seen += 1;
false
});
assert_eq!(seen, 1);
assert!(stats.truncated);
}
#[test]
fn walk_groups_and_hidden_layers() {
let mut hidden = line(0.0, 0.0, 9.0, 9.0);
hidden.layer = Some("off".into());
let group = Entity::new(EntityKind::Group {
group_kind: crate::model::GroupKind::Cell,
name: None,
origin: None,
children: vec![line(0.0, 0.0, 1.0, 1.0), hidden],
});
let mut doc = doc_with(vec![group], vec![]);
doc.layers.push(Layer {
name: "off".into(),
visible: false,
..Layer::default()
});
let hits = collect(&doc, 8);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].1, 1);
doc.layers[0].visible = true;
doc.layers[0].frozen = true;
assert_eq!(collect(&doc, 8).len(), 1);
doc.layers[0].frozen = false;
assert_eq!(collect(&doc, 8).len(), 2);
}
#[test]
fn walk_missing_model_and_block() {
let doc = doc_with(vec![insert("nope", 0.0, 0.0)], vec![]);
let mut n = 0;
doc.walk(5, 8, |_, _| n += 1);
assert_eq!(n, 0);
doc.walk(0, 8, |_, _| n += 1);
assert_eq!(n, 1);
}
#[test]
fn dimension_block_expanded() {
let blk = block("*D1", vec![line(0.0, 0.0, 3.0, 0.0)]);
let dim = Entity::new(EntityKind::Dimension {
dimension_type: crate::model::DimensionType::Linear,
points: vec![Point3::xy(100.0, 100.0)],
text_position: None,
measurement: None,
text: None,
block: Some("*D1".into()),
style: None,
});
let doc = doc_with(vec![dim], vec![blk]);
let bb = doc.bbox(0).unwrap();
assert_eq!(bb.max.x, 3.0);
}
#[test]
fn bbox_of_shapes() {
let circle = Entity::new(EntityKind::Circle {
center: Point3::xy(5.0, 5.0),
radius: 2.0,
normal: Vec3::Z,
});
let poly = Entity::new(EntityKind::Polyline {
vertices: vec![
Vertex {
position: Point3::xy(0.0, 0.0),
bulge: 1.0,
..Vertex::default()
},
Vertex::at(Point3::xy(2.0, 0.0)),
],
closed: false,
normal: Vec3::Z,
});
let doc = doc_with(vec![circle], vec![]);
let bb = doc.bbox(0).unwrap();
assert!((bb.min.x - 3.0).abs() < 1e-9 && (bb.max.y - 7.0).abs() < 1e-9);
let doc = doc_with(vec![poly], vec![]);
let bb = doc.bbox(0).unwrap();
assert!((bb.min.y + 1.0).abs() < 1e-9 && (bb.max.x - 2.0).abs() < 1e-9);
assert!(doc_with(vec![], vec![]).bbox(0).is_none());
assert!(doc_with(vec![], vec![]).bbox(3).is_none());
}
#[test]
fn flipped_normal_keeps_wcs_center_and_flips_angles() {
let neg = Vec3::new(0.0, 0.0, -1.0);
let circle = Entity::new(EntityKind::Circle {
center: Point3::xy(5.0, 0.0),
radius: 1.0,
normal: neg,
});
let bb = doc_with(vec![circle], vec![]).bbox(0).unwrap();
assert!((bb.min.x - 4.0).abs() < 1e-9 && (bb.max.x - 6.0).abs() < 1e-9);
let arc = Entity::new(EntityKind::Arc {
center: Point3::xy(10.0, 10.0),
radius: 2.0,
start_angle: 0.0,
end_angle: PI / 2.0,
normal: neg,
});
let bb = doc_with(vec![arc], vec![]).bbox(0).unwrap();
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
assert!(
near(bb.min.x, 8.0)
&& near(bb.max.x, 10.0)
&& near(bb.min.y, 10.0)
&& near(bb.max.y, 12.0),
"{bb:?}"
);
}
#[test]
fn bulged_polyline_with_flipped_normal_bulges_the_other_way() {
let mk = |normal: Vec3| {
Entity::new(EntityKind::Polyline {
vertices: vec![
Vertex {
position: Point3::xy(0.0, 0.0),
bulge: 1.0,
..Vertex::default()
},
Vertex::at(Point3::xy(2.0, 0.0)),
],
closed: false,
normal,
})
};
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let up = doc_with(vec![mk(Vec3::Z)], vec![]).bbox(0).unwrap();
assert!(near(up.min.y, -1.0) && near(up.max.y, 0.0));
let down = doc_with(vec![mk(Vec3::new(0.0, 0.0, -1.0))], vec![])
.bbox(0)
.unwrap();
assert!(near(down.min.y, 0.0) && near(down.max.y, 1.0), "{down:?}");
assert!(near(down.min.x, 0.0) && near(down.max.x, 2.0));
}
#[test]
fn bbox_with_can_ignore_images() {
let poly = line(0.0, 0.0, 10.0, 10.0);
let image = Entity::new(EntityKind::Image {
path: None,
position: Point3::xy(-50.0, -50.0),
u_vector: Vec3::new(100.0, 0.0, 0.0),
v_vector: Vec3::new(0.0, 100.0, 0.0),
size_px: None,
});
let doc = doc_with(vec![poly, image.clone()], vec![]);
assert!((doc.bbox(0).unwrap().max.x - 50.0).abs() < 1e-9);
let bb = doc
.bbox_with(
0,
&BBoxOptions {
include_images: false,
..BBoxOptions::default()
},
)
.unwrap();
assert!((bb.max.x - 10.0).abs() < 1e-9);
let only = doc_with(vec![image], vec![]);
assert!(
only.bbox_with(
0,
&BBoxOptions {
include_images: false,
..BBoxOptions::default()
}
)
.is_none()
);
}
#[test]
fn aligned_text_bbox_covers_baseline() {
let t = Entity::new(EntityKind::Text {
position: Point3::xy(0.0, 0.0),
end_point: Some(Point3::xy(10.0, 0.0)),
height: 2.0,
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
value: "x".into(),
style: None,
halign: HAlign::Aligned,
valign: VAlign::Baseline,
normal: Vec3::Z,
});
let bb = doc_with(vec![t], vec![]).bbox(0).unwrap();
assert!(
(bb.max.x - 10.0).abs() < 1e-9
&& (bb.max.y - 2.0).abs() < 1e-9
&& bb.min.y.abs() < 1e-9
);
}
#[test]
fn insert_with_flipped_normal_uses_wcs_position() {
let blk = block("b", vec![line(0.0, 0.0, 1.0, 0.0)]);
let mut ins = insert("b", 10.0, 3.0);
if let EntityKind::Insert { normal, .. } = &mut ins.kind {
*normal = Vec3::new(0.0, 0.0, -1.0);
}
let doc = doc_with(vec![ins], vec![blk]);
let mut pts = Vec::new();
doc.walk(0, 8, |e, ctx| {
if let EntityKind::Line { start, end } = &e.kind {
pts.push((
ctx.transform.apply_point(*start),
ctx.transform.apply_point(*end),
));
}
});
assert_eq!(pts.len(), 1);
let (s, e) = pts[0];
assert!((s.x - 10.0).abs() < 1e-9 && (s.y - 3.0).abs() < 1e-9);
assert!((e.x - 9.0).abs() < 1e-9 && (e.y - 3.0).abs() < 1e-9);
}
#[test]
fn colors() {
let mut doc = doc_with(vec![], vec![]);
doc.layers.push(Layer {
name: "L".into(),
color: Color::Aci { index: 1 },
..Layer::default()
});
doc.layers.push(Layer {
name: "0".into(),
color: Color::Rgb { r: 1, g: 2, b: 3 },
..Layer::default()
});
let mut e = Entity::new(EntityKind::Point {
position: Point3::default(),
});
assert_eq!(e.resolved_color(&doc), (1, 2, 3));
e.layer = Some("L".into());
assert_eq!(e.resolved_color(&doc), (255, 0, 0));
e.layer = Some("missing".into());
assert_eq!(e.resolved_color(&doc), (0, 0, 0));
e.color = Color::Aci { index: 5 };
assert_eq!(e.resolved_color(&doc), (0, 0, 255));
e.color = Color::Aci { index: 7 };
assert_eq!(e.resolved_color(&doc), (0, 0, 0));
e.color = Color::Rgb { r: 9, g: 8, b: 7 };
assert_eq!(e.resolved_color(&doc), (9, 8, 7));
e.color = Color::ByBlock;
assert_eq!(e.resolved_color(&doc), (0, 0, 0));
}
#[test]
fn byblock_and_layer_inheritance_through_insert() {
let mut inner = line(0.0, 0.0, 1.0, 0.0);
inner.color = Color::ByBlock;
inner.layer = Some("0".into());
let blk = block("b", vec![inner]);
let mut ins = insert("b", 0.0, 0.0);
ins.color = Color::Aci { index: 3 };
ins.layer = Some("walls".into());
let mut doc = doc_with(vec![ins], vec![blk]);
doc.layers.push(Layer {
name: "walls".into(),
visible: true,
..Layer::default()
});
let mut seen = None;
doc.walk(0, 8, |e, ctx| {
seen = Some((e.resolved_color_in(&doc, ctx), ctx.layer_name(e).to_owned()));
});
assert_eq!(seen, Some(((0, 255, 0), "walls".to_owned())));
}
#[test]
fn byblock_chain_uses_layer_of_insert() {
let mut inner = line(0.0, 0.0, 1.0, 0.0);
inner.color = Color::ByBlock;
let blk = block("b", vec![inner]);
let ins = insert("b", 0.0, 0.0); let mut doc = doc_with(vec![ins], vec![blk]);
doc.layers.push(Layer {
name: "0".into(),
color: Color::Aci { index: 1 },
visible: true,
..Layer::default()
});
let mut seen = None;
doc.walk(0, 8, |e, ctx| seen = Some(e.resolved_color_in(&doc, ctx)));
assert_eq!(seen, Some((255, 0, 0)));
}
#[test]
fn type_names() {
assert_eq!(line(0.0, 0.0, 1.0, 1.0).kind.type_name(), "line");
assert_eq!(insert("a", 0.0, 0.0).kind.type_name(), "insert");
}
#[test]
fn clockwise_hatch_arc_and_ellipse_bbox() {
use crate::HatchLoop;
let cw_arc = Entity::new(EntityKind::Hatch {
loops: vec![HatchLoop {
edges: vec![HatchEdge::Arc {
center: Point3::default(),
radius: 2.0,
start_angle: PI / 2.0,
end_angle: 0.0,
ccw: false,
}],
external: true,
}],
solid: true,
pattern: None,
pattern_scale: 1.0,
pattern_angle: 0.0,
normal: Vec3::Z,
});
let bb = doc_with(vec![cw_arc], vec![]).bbox(0).unwrap();
assert!(
bb.min.x >= -1e-9
&& bb.min.y >= -1e-9
&& (bb.max.x - 2.0).abs() < 1e-9
&& (bb.max.y - 2.0).abs() < 1e-9,
"unexpected clockwise hatch arc bbox: {bb:?}"
);
let cw_ellipse = Entity::new(EntityKind::Hatch {
loops: vec![HatchLoop {
edges: vec![HatchEdge::Ellipse {
center: Point3::default(),
major_axis: Vec3::new(3.0, 0.0, 0.0),
ratio: 0.5,
start_param: PI / 2.0,
end_param: 0.0,
ccw: false,
}],
external: true,
}],
solid: true,
pattern: None,
pattern_scale: 1.0,
pattern_angle: 0.0,
normal: Vec3::Z,
});
let bb = doc_with(vec![cw_ellipse], vec![]).bbox(0).unwrap();
assert!(
bb.min.x >= -1e-9
&& bb.min.y >= -1e-9
&& (bb.max.x - 3.0).abs() < 1e-9
&& (bb.max.y - 1.5).abs() < 1e-9,
"unexpected clockwise hatch ellipse bbox: {bb:?}"
);
}
#[test]
fn entity_bbox_and_distance_xy_distinguish_diagonal_line_from_box() {
let diag = line(0.0, 0.0, 10.0, 10.0);
let bb = diag.bbox().unwrap();
assert_eq!(
(bb.min.x, bb.min.y, bb.max.x, bb.max.y),
(0.0, 0.0, 10.0, 10.0)
);
let d_on = entity_distance_xy(&diag, &Transform::identity(), (5.0, 5.0)).unwrap();
let d_off = entity_distance_xy(&diag, &Transform::identity(), (0.0, 10.0)).unwrap();
assert!(d_on < 1e-12);
assert!((d_off - 5.0 * 2.0_f64.sqrt()).abs() < 1e-9);
let circle = Entity::circle(Point3::xy(0.0, 0.0), 5.0);
assert!(
(entity_distance_xy(&circle, &Transform::identity(), (0.0, 0.0)).unwrap() - 5.0).abs()
< 1e-3
);
assert!(entity_distance_xy(&circle, &Transform::identity(), (5.0, 0.0)).unwrap() < 1e-6);
let mut hidden = line(0.0, 0.0, 4.0, 0.0).on_layer("FROZEN");
hidden.id = Some(9);
let mut doc = doc_with(vec![hidden], vec![]);
doc.layers.push(Layer {
name: "FROZEN".into(),
visible: true,
frozen: true,
..Layer::default()
});
assert!(doc.bbox(0).is_none());
assert!(
doc.bbox_all_layers_with(0, &BBoxOptions::default())
.is_some()
);
}
}
#[cfg(test)]
mod picking_regressions {
use super::*;
#[test]
fn circular_picking_is_exact_between_old_sample_vertices() {
let circle = Entity::circle(Point3::xy(0.0, 0.0), 1000.0);
let angle = 0.037_f64;
let point = (1000.001 * angle.cos(), 1000.001 * angle.sin());
let d = entity_distance_xy(&circle, &Transform::identity(), point).unwrap_or(f64::INFINITY);
assert!((d - 0.001).abs() < 1e-9);
let arc = Entity::new(EntityKind::Arc {
center: Point3::default(),
radius: 5.0,
start_angle: 0.0,
end_angle: std::f64::consts::FRAC_PI_2,
normal: Vec3::Z,
});
let d =
entity_distance_xy(&arc, &Transform::identity(), (-5.0, 0.0)).unwrap_or(f64::INFINITY);
assert!((d - 50.0_f64.sqrt()).abs() < 1e-9);
}
}