use super::{Cell, Placement, Position, compose, repeat_count, repeat_offset, transform_element};
use crate::geometry::{self, BooleanOp, Ring};
use crate::{Element, Error, Layout, Point, ReadOptions, Result};
use sha1::{Digest, Sha1};
use std::collections::{BTreeSet, HashMap};
use std::fs::File;
use std::io::{Read, Seek};
use std::path::Path;
#[derive(Clone, Copy, Debug, serde::Serialize)]
pub struct Window {
lower: Point,
upper: Point,
}
impl Window {
pub fn new(lower: Point, upper: Point) -> Result<Self> {
if lower.x >= upper.x || lower.y >= upper.y {
return Err(Error::invalid("window needs x0 < x1 and y0 < y1"));
}
Ok(Self { lower, upper })
}
fn bounds(ring: &Ring) -> Option<Self> {
let first = *ring.first()?;
let mut bounds = Self {
lower: first,
upper: first,
};
for &p in &ring[1..] {
bounds.lower.x = bounds.lower.x.min(p.x);
bounds.lower.y = bounds.lower.y.min(p.y);
bounds.upper.x = bounds.upper.x.max(p.x);
bounds.upper.y = bounds.upper.y.max(p.y);
}
Some(bounds)
}
fn intersection(self, other: Self) -> Option<Self> {
Self::new(
Point {
x: self.lower.x.max(other.lower.x),
y: self.lower.y.max(other.lower.y),
},
Point {
x: self.upper.x.min(other.upper.x),
y: self.upper.y.min(other.upper.y),
},
)
.ok()
}
fn contains(self, other: Self) -> bool {
self.lower.x <= other.lower.x
&& self.lower.y <= other.lower.y
&& self.upper.x >= other.upper.x
&& self.upper.y >= other.upper.y
}
}
pub struct ClipOptions<'a> {
pub read: ReadOptions<'a>,
pub placement_limit: usize,
pub output_vertex_limit: usize,
pub tolerance_dbu: f64,
}
impl Default for ClipOptions<'_> {
fn default() -> Self {
Self {
read: ReadOptions::default(),
placement_limit: super::DEFAULT_EXPANSION_LIMIT,
output_vertex_limit: 4_000_000,
tolerance_dbu: 0.25,
}
}
}
struct HashedInput<'a> {
file: &'a mut File,
hash: &'a mut Sha1,
}
impl Read for HashedInput<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.file.read(buf)?;
self.hash.update(&buf[..n]);
Ok(n)
}
}
fn placements(
graph: &Layout,
top: &str,
shapes: &BTreeSet<usize>,
limit: usize,
) -> Result<Vec<Vec<Placement>>> {
let index: HashMap<_, _> = graph
.cells
.iter()
.enumerate()
.map(|(i, c)| (c.name.as_str(), i))
.collect();
let root = *index
.get(top)
.ok_or_else(|| Error::invalid(format!("unknown top cell {top:?}")))?;
let mut result = vec![Vec::new(); graph.cells.len()];
let mut stack = vec![(root, Placement::identity())];
let mut remaining = limit - 1;
while let Some((cell, placement)) = stack.pop() {
if shapes.contains(&cell) {
result[cell].push(placement);
}
for e in &graph.cells[cell].elements {
if let Element::Reference {
cell,
origin,
transform,
array,
} = e.unadorned()
{
let count = repeat_count(array.as_ref());
if count > remaining as u64 {
return Err(Error::invalid(format!(
"clip placement expansion exceeds limit {limit}"
)));
}
remaining -= count as usize;
let transform = compose(placement.transform, *transform)?;
for i in 0..count {
let offset = repeat_offset(array.as_ref(), i);
let origin = placement.map(offset.add(Position::point(*origin))?)?;
stack.push((index[cell.as_str()], Placement { origin, transform }));
}
}
}
}
Ok(result)
}
struct Output<'a> {
windows: &'a [Window],
cells: &'a mut [Cell],
remaining: usize,
}
impl Output<'_> {
fn add(&mut self, element: &Element, ring: Ring) -> Result<()> {
if ring.len() < 3 {
return Ok(());
}
let bounds = Window::bounds(&ring).expect("nonempty ring");
let layer = element.layer().expect("placed shape has a layer");
for (&window, cell) in self.windows.iter().zip(self.cells.iter_mut()) {
let Some(area) = window.intersection(bounds) else {
continue;
};
let clipped = if window.contains(bounds) {
geometry::fracture(std::slice::from_ref(&ring), 8_190)?
} else {
let box_ring = geometry::rectangle(area.lower, area.upper)?;
let clipped = geometry::boolean(
std::slice::from_ref(&ring),
&[box_ring],
BooleanOp::Intersection,
)?;
geometry::fracture(&clipped, 8_190)?
};
for points in clipped {
self.remaining = self
.remaining
.checked_sub(points.len())
.ok_or_else(|| Error::invalid("clip output vertex budget exceeded"))?;
cell.elements.push(Element::Polygon { layer, points });
}
}
Ok(())
}
}
fn material(e: &Element) -> bool {
match e.unadorned() {
Element::Repeated { element, .. } => material(element),
Element::Reference { .. } | Element::Text { .. } => false,
_ => true,
}
}
pub fn clip_file(
path: impl AsRef<Path>,
top: &str,
windows: &[Window],
options: ClipOptions<'_>,
) -> Result<Layout> {
if windows.is_empty() || options.placement_limit == 0 || options.output_vertex_limit == 0 {
return Err(Error::invalid(
"clip requires windows and positive resource limits",
));
}
if !options.tolerance_dbu.is_finite() || options.tolerance_dbu <= 0.0 {
return Err(Error::invalid("tolerance must be positive and finite"));
}
let mut file = File::open(path)?;
let mut first = Sha1::new();
let mut shapes = BTreeSet::new();
let (graph, _) = options.read.read_filtered(
HashedInput {
file: &mut file,
hash: &mut first,
},
false,
&mut |cell, element| {
if material(element) {
shapes.insert(cell);
}
Ok(matches!(element.unadorned(), Element::Reference { .. }))
},
)?;
let placements = placements(&graph, top, &shapes, options.placement_limit)?;
let mut output = Layout::new("CLIPS", graph.dbu_meters)?;
for index in 1..=windows.len() {
output.add_cell(format!("WIN_{index}"))?;
}
let mut target = Output {
windows,
cells: &mut output.cells,
remaining: options.output_vertex_limit,
};
let mut second = Sha1::new();
file.rewind()?;
options.read.read_filtered(
HashedInput {
file: &mut file,
hash: &mut second,
},
true,
&mut |cell, element| {
let Some(cell_placements) = placements.get(cell).filter(|values| !values.is_empty())
else {
return Ok(false);
};
if !material(element) {
return Ok(false);
}
let (base, rep) = match element.unadorned() {
Element::Repeated { element, array } => (element.unadorned(), Some(array)),
base => (base, None),
};
let count = repeat_count(rep);
if count > (options.placement_limit / cell_placements.len()) as u64 {
return Err(Error::invalid(format!(
"clip record expansion exceeds limit {}",
options.placement_limit
)));
}
for &p in cell_placements {
for i in 0..count {
let p = p.shifted(repeat_offset(rep, i))?;
let mut value = base.clone();
transform_element(&mut value, p)?;
let ring = super::element_outline(&value, options.tolerance_dbu)?;
target.add(&value, ring)?;
}
}
Ok(false)
},
)?;
if first.finalize() != second.finalize() {
return Err(Error::invalid("input changed between the two clip scans"));
}
Ok(output)
}