layouttk 0.1.2

Integer-grid GDSII and OASIS layout processing with hierarchy-aware extraction
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use super::{Frame, Ring, signed_twice_area};
use crate::{Error, Point, Result, Transform};
use std::f64::consts::{FRAC_PI_2, PI, TAU};

const MAX_VERTICES: usize = 1_000_000;
// An f64 carries all integer DBU and half-DBU rounding information in this range.
const FLOAT_LIMIT: f64 = (1_u64 << 51) as f64;

pub(super) fn validate_tolerance(tolerance: f64) -> Result<()> {
    if tolerance.is_finite() && tolerance > 0.0 {
        Ok(())
    } else {
        Err(Error::invalid("tolerance must be positive and finite"))
    }
}

pub(super) fn arc_steps(radius: f64, sweep: f64, tolerance: f64) -> Result<usize> {
    validate_tolerance(tolerance)?;
    // sagitta = 2*r*sin(step/4)^2, stable for very small tolerances.
    let step = (4.0 * (tolerance / (2.0 * radius)).min(1.0).sqrt().asin()).min(FRAC_PI_2);
    let count = (sweep.abs() / step).ceil().max(1.0);
    if count > MAX_VERTICES as f64 {
        return Err(Error::invalid(
            "curve needs over one million vertices at the requested tolerance",
        ));
    }
    Ok(count as usize)
}

fn rounded(value: f64) -> Result<i128> {
    if !value.is_finite() || value.abs() > FLOAT_LIMIT {
        return Err(Error::invalid(
            "floating-point construction exceeds its local DBU precision range",
        ));
    }
    Ok(value.round() as i128)
}

fn point_i128(x: i128, y: i128) -> Result<Point> {
    let coordinate =
        |v| i64::try_from(v).map_err(|_| Error::invalid("geometry result exceeds i64 DBU"));
    Ok(Point {
        x: coordinate(x)?,
        y: coordinate(y)?,
    })
}

fn relative_point(origin: Point, x: f64, y: f64) -> Result<Point> {
    point_i128(
        i128::from(origin.x) + rounded(x)?,
        i128::from(origin.y) + rounded(y)?,
    )
}

fn finished(mut ring: Ring) -> Result<Ring> {
    ring.dedup();
    if ring.len() > 1 && ring.first() == ring.last() {
        ring.pop();
    }
    if ring.len() < 3 {
        return Err(Error::invalid("polygon collapses on the integer DBU grid"));
    }
    Frame::new(ring.iter())?;
    if signed_twice_area(&ring) == 0 {
        return Err(Error::invalid(
            "polygon has zero signed area on the integer DBU grid",
        ));
    }
    Ok(ring)
}

/// Counterclockwise rectangle, with either pair of opposite corners accepted.
pub fn rectangle(a: Point, b: Point) -> Result<Ring> {
    let (x0, x1) = (a.x.min(b.x), a.x.max(b.x));
    let (y0, y1) = (a.y.min(b.y), a.y.max(b.y));
    if x0 == x1 || y0 == y1 {
        return Err(Error::invalid(
            "rectangle must have positive width and height",
        ));
    }
    Ok(vec![
        Point { x: x0, y: y0 },
        Point { x: x1, y: y0 },
        Point { x: x1, y: y1 },
        Point { x: x0, y: y1 },
    ])
}

fn check_radius(radius: f64) -> Result<()> {
    if radius > 0.0 && radius.is_finite() && radius <= FLOAT_LIMIT {
        Ok(())
    } else {
        Err(Error::invalid(
            "radius must be positive, finite and within the local DBU precision range",
        ))
    }
}

/// Approximate an axis-aligned ellipse. The chord error is bounded by tolerance
/// before snapping. Snapping adds at most sqrt(0.5) DBU per vertex.
pub fn ellipse(center: Point, radius_x: f64, radius_y: f64, tolerance: f64) -> Result<Ring> {
    check_radius(radius_x)?;
    check_radius(radius_y)?;
    let quarter = arc_steps(radius_x.max(radius_y), FRAC_PI_2, tolerance)?;
    let count = 4 * quarter;
    if count > MAX_VERTICES {
        return Err(Error::invalid("ellipse exceeds one million vertices"));
    }
    let mut ring = Ring::with_capacity(count);
    for i in 0..count {
        let (s, c) = (TAU * i as f64 / count as f64).sin_cos();
        ring.push(relative_point(center, radius_x * c, radius_y * s)?);
    }
    finished(ring)
}

/// A counterclockwise regular polygon given its circumradius and angle of its
/// first vertex, measured counterclockwise from the positive X axis.
pub fn regular_polygon(center: Point, radius: f64, sides: usize, angle_deg: f64) -> Result<Ring> {
    check_radius(radius)?;
    if !(3..=MAX_VERTICES).contains(&sides) || !angle_deg.is_finite() {
        return Err(Error::invalid(
            "regular polygon needs 3..=1000000 sides and a finite angle",
        ));
    }
    let start = angle_deg.rem_euclid(360.0).to_radians();
    let mut ring = Ring::with_capacity(sides);
    for i in 0..sides {
        let (s, c) = (start + TAU * i as f64 / sides as f64).sin_cos();
        ring.push(relative_point(center, radius * c, radius * s)?);
    }
    finished(ring)
}

/// Reflect about the local X axis, magnify, rotate about `origin`, then
/// translate. Unit-magnification quarter turns are exact over the i64 domain.
pub fn transform_points(
    points: &[Point],
    origin: Point,
    translation: Point,
    transform: Transform,
) -> Result<Ring> {
    if !transform.angle_deg.is_finite()
        || !transform.magnification.is_finite()
        || transform.magnification <= 0.0
    {
        return Err(Error::invalid(
            "transform needs a finite angle and positive finite magnification",
        ));
    }
    let angle = transform.angle_deg.rem_euclid(360.0);
    let quarter_turn = angle % 90.0 == 0.0;
    let (sin, cos) = angle.to_radians().sin_cos();
    let ox = i128::from(origin.x) + i128::from(translation.x);
    let oy = i128::from(origin.y) + i128::from(translation.y);
    points
        .iter()
        .map(|p| {
            let dx = i128::from(p.x) - i128::from(origin.x);
            let dy = i128::from(p.y) - i128::from(origin.y);
            let dy = if transform.reflect_x { -dy } else { dy };
            let (x, y) = if quarter_turn {
                match (angle / 90.0) as u8 {
                    0 => (dx, dy),
                    1 => (-dy, dx),
                    2 => (-dx, -dy),
                    _ => (dy, -dx),
                }
            } else {
                (dx, dy)
            };
            if quarter_turn && transform.magnification == 1.0 {
                return point_i128(ox + x, oy + y);
            }
            if x.unsigned_abs().max(y.unsigned_abs()) > FLOAT_LIMIT as u128 {
                return Err(Error::invalid(
                    "transform exceeds its local DBU precision range",
                ));
            }
            let (x, y) = (x as f64, y as f64);
            let (x, y) = if quarter_turn {
                (x, y)
            } else {
                (x * cos - y * sin, x * sin + y * cos)
            };
            point_i128(
                ox + rounded(x * transform.magnification)?,
                oy + rounded(y * transform.magnification)?,
            )
        })
        .collect()
}

/// Round each corner of one contour using a tangent circular arc. Oversized
/// radii are reduced locally to consume at most half of each adjacent edge.
/// Both convex and reentrant corners follow the input contour's winding.
pub fn fillet(points: &[Point], radius: f64, tolerance: f64) -> Result<Ring> {
    fillet_radii(points, &[radius], tolerance)
}

/// Round each vertex with its own radius. A single radius applies to every corner.
pub fn fillet_radii(points: &[Point], radii: &[f64], tolerance: f64) -> Result<Ring> {
    validate_tolerance(tolerance)?;
    let ring = finished(points.to_vec())?;
    if radii.len() != 1 && (radii.len() != ring.len() || ring.len() != points.len()) {
        return Err(Error::invalid(
            "provide a scalar radius or one radius per distinct contour vertex",
        ));
    }
    if radii.iter().any(|r| !r.is_finite() || *r < 0.0) {
        return Err(Error::invalid(
            "fillet radii must be nonnegative and finite",
        ));
    }
    let mut out = Vec::new();
    for (i, &vertex) in ring.iter().enumerate() {
        let radius = if radii.len() == 1 { radii[0] } else { radii[i] };
        if radius == 0.0 {
            out.push(vertex);
            continue;
        }
        let previous = ring[(i + ring.len() - 1) % ring.len()];
        let next = ring[(i + 1) % ring.len()];
        let (dx, dy) = (
            (vertex.x - previous.x) as f64,
            (vertex.y - previous.y) as f64,
        );
        let (ex, ey) = ((next.x - vertex.x) as f64, (next.y - vertex.y) as f64);
        let (incoming, outgoing) = (dx.hypot(dy), ex.hypot(ey));
        let (ux, uy, vx, vy) = (dx / incoming, dy / incoming, ex / outgoing, ey / outgoing);
        let turn = (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
        if (PI - turn.abs()).abs() <= f64::EPSILON {
            return Err(Error::invalid("cannot fillet a reversing edge"));
        }
        if turn.abs() <= f64::EPSILON {
            out.push(vertex);
            continue;
        }
        let tangent = (turn.abs() / 2.0).tan();
        let trim = (radius * tangent).min(incoming.min(outgoing) / 2.0);
        let r = trim / tangent;
        let signed_r = turn.signum() * r;
        let (cx, cy) = (-ux * trim - uy * signed_r, -uy * trim + ux * signed_r);
        let (rx, ry) = (uy * signed_r, -ux * signed_r);
        let count = arc_steps(r, turn, tolerance)?;
        if out.len() + count + 1 > MAX_VERTICES {
            return Err(Error::invalid("fillet exceeds one million vertices"));
        }
        out.push(relative_point(vertex, -ux * trim, -uy * trim)?);
        for j in 1..count {
            let (s, c) = (turn * j as f64 / count as f64).sin_cos();
            out.push(relative_point(
                vertex,
                cx + c * rx - s * ry,
                cy + s * rx + c * ry,
            )?);
        }
        out.push(relative_point(vertex, vx * trim, vy * trim)?);
    }
    finished(out)
}

/// Scale points independently around a fixed origin, rounding once to integer DBU.
pub fn scale_points(points: &[Point], origin: Point, sx: f64, sy: f64) -> Result<Ring> {
    if !sx.is_finite() || !sy.is_finite() {
        return Err(Error::invalid("scale factors must be finite"));
    }
    fn scale(v: i64, origin: i64, factor: f64) -> Result<i64> {
        let delta = i128::from(v) - i128::from(origin);
        let offset = if factor == 1.0 {
            delta
        } else if factor == -1.0 {
            -delta
        } else if factor == 0.0 {
            0
        } else {
            if delta.unsigned_abs() > FLOAT_LIMIT as u128 {
                return Err(Error::invalid("scale exceeds local DBU precision"));
            }
            rounded(delta as f64 * factor)?
        };
        i64::try_from(i128::from(origin) + offset)
            .map_err(|_| Error::invalid("scaled coordinate exceeds i64 DBU"))
    }
    points
        .iter()
        .map(|p| {
            Ok(Point {
                x: scale(p.x, origin.x, sx)?,
                y: scale(p.y, origin.y, sy)?,
            })
        })
        .collect()
}

/// Reflect around the line passing through a and b.
pub fn mirror_points(points: &[Point], a: Point, b: Point) -> Result<Ring> {
    let dx = i128::from(b.x) - i128::from(a.x);
    let dy = i128::from(b.y) - i128::from(a.y);
    if dx == 0 && dy == 0 {
        return Err(Error::invalid("a mirror axis needs two distinct points"));
    }
    if dx == 0 {
        return scale_points(points, a, -1.0, 1.0);
    }
    if dy == 0 {
        return scale_points(points, a, 1.0, -1.0);
    }
    let angle = if dx == dy {
        90.0
    } else if dx == -dy {
        270.0
    } else {
        2.0 * (dy as f64).atan2(dx as f64).to_degrees()
    };
    transform_points(
        points,
        a,
        Point::default(),
        Transform {
            angle_deg: angle,
            magnification: 1.0,
            reflect_x: true,
        },
    )
}

/// Select a pre-snap chord error in DBU or the exact number of contour vertices.
#[derive(Clone, Copy, Debug)]
pub enum Sampling {
    Tolerance(f64),
    Vertices(usize),
}

/// Annular or solid elliptical sector, between geometric polar angles in degrees.
/// A positive sweep is counterclockwise. A full revolution returns separate outer and hole rings.
pub fn elliptic_sector(
    center: Point,
    outer: (f64, f64),
    inner: Option<(f64, f64)>,
    start_deg: f64,
    sweep_deg: f64,
    sampling: Sampling,
) -> Result<Vec<Ring>> {
    check_radius(outer.0)?;
    check_radius(outer.1)?;
    if let Sampling::Tolerance(tolerance) = sampling {
        validate_tolerance(tolerance)?;
    }
    if !start_deg.is_finite()
        || !sweep_deg.is_finite()
        || sweep_deg == 0.0
        || sweep_deg.abs() > 360.0
    {
        return Err(Error::invalid(
            "sector needs a finite start angle and a nonzero sweep of at most 360 degrees",
        ));
    }
    if let Some((rx, ry)) = inner {
        check_radius(rx)?;
        check_radius(ry)?;
        if rx > outer.0 || ry > outer.1 || (rx, ry) == outer {
            return Err(Error::invalid(
                "inner ellipse must fit inside the outer ellipse",
            ));
        }
    }
    let full = sweep_deg.abs() == 360.0;
    // All generated region contours follow winding conventions, even for clockwise sweeps.
    let begin = if sweep_deg < 0.0 {
        start_deg.rem_euclid(360.0) + sweep_deg
    } else {
        start_deg.rem_euclid(360.0)
    };
    let begin = begin.to_radians();
    let end = begin + sweep_deg.abs().to_radians();
    let (outer_count, inner_count) = match sampling {
        Sampling::Tolerance(_) => (None, None),
        Sampling::Vertices(n) => {
            if n > MAX_VERTICES {
                return Err(Error::invalid("sector exceeds one million vertices"));
            }
            let split = if inner.is_some() {
                n / 2
            } else {
                usize::from(!full)
            };
            let count = n.saturating_sub(split);
            let min = if full { 3 } else { 2 };
            if count < min || (inner.is_some() && split < min) {
                return Err(Error::invalid("too few vertices for the requested sector"));
            }
            (Some(count), Some(split))
        }
    };
    let arc = |(rx, ry): (f64, f64), exact: Option<usize>| -> Result<Ring> {
        let param = |a: f64| (rx * a.sin()).atan2(ry * a.cos());
        let start = param(begin);
        let sweep = if full {
            TAU
        } else {
            (param(end) - start).rem_euclid(TAU)
        };
        let edges = match (exact, sampling) {
            (Some(n), _) => n - usize::from(!full),
            (_, Sampling::Tolerance(tol)) => arc_steps(rx.max(ry), sweep, tol)?,
            _ => unreachable!(),
        };
        let count = edges + usize::from(!full);
        (0..count)
            .map(|i| {
                let (s, c) = (start + sweep * (i as f64) / (edges as f64)).sin_cos();
                relative_point(center, rx * c, ry * s)
            })
            .collect()
    };
    let finish = |ring: Ring| -> Result<Ring> {
        let count = ring.len();
        let result = finished(ring)?;
        if matches!(sampling, Sampling::Vertices(_)) && result.len() != count {
            return Err(Error::invalid(
                "chosen grid cannot resolve the requested vertex count",
            ));
        }
        Ok(result)
    };
    let mut outer_ring = arc(outer, outer_count)?;
    let mut result = Vec::new();
    if let Some(radii) = inner {
        let mut hole = arc(radii, inner_count)?;
        hole.reverse();
        if full {
            result.push(finish(outer_ring)?);
            result.push(finish(hole)?);
            return Ok(result);
        }
        outer_ring.extend(hole);
    } else if !full {
        outer_ring.push(center);
    }
    result.push(finish(outer_ring)?);
    Ok(result)
}