Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,14 @@ The format of this changelog is based on
- Schematic `render!` to a `Cell` or a `SolidModel` with `strict=:no` logs a component
whose geometry fails to build and renders it as empty geometry, instead of throwing.
(#287)
- Rendering to a `SolidModel` applies entity styles instead of silently dropping them.
Styles without a kernel-native implementation are discretized through `to_polygons`,
with a warning on OpenCascade.
- `Rounded` circles and ellipses render to an OpenCascade `SolidModel` as exact ellipses
instead of recursing until the stack overflows.
- `StyleDict` on an entity other than a `ClippedPolygon` or `CurvilinearRegion`, such as a
`Rectangle`, applies its style at `[1]` instead of recursing until the stack overflows,
and throws an `ArgumentError` if it has styles at other indices.
- `LineSegment`s can be placed in coordinate systems of a different coordinate type and
transformed through references, which previously threw a `MethodError`, and their
`bounds` (and `lowerleft`/`upperright`) now give their extent instead of a zero
Expand Down
2 changes: 2 additions & 0 deletions docs/src/concepts/solidmodels.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ flatten --> to_primitives --> physical groups --> postrender ops --> fragment &

Each element is converted to kernel-native geometry via `to_primitives(sm, entity)`. OpenCascade represents curves and ellipses as exact geometry. Exact arcs produce smoother meshes with fewer elements—see the example [here](./geometry.md#Solid-Models).

Styles are applied to styled entities. Styles that don't change the geometry, such as [`MeshSized`](@ref), keep native curves, and `Rounded` keeps exact arcs on OpenCascade. Any other style, including a user-defined one, is applied through `to_polygons` as in 2D rendering, which discretizes curves; OpenCascade warns when that happens.

### 3. Physical group creation

Rendered entities are grouped by their mapped layer name. The `map_meta` function controls this mapping; when rendering through a `SolidModelTarget`, it applies rules for levelwise layers (appending `_L1`, `_L2`, etc.) and indexed layers (appending `_1`, `_2`, etc.). At this stage, entities also receive mesh sizing information from [`MeshSized`](@ref) metadata.
Expand Down
16 changes: 13 additions & 3 deletions src/curvilinear.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1957,6 +1957,9 @@ styled_loop(n::PolyNode, sty; kwargs...) = styled_loop(Polygon(contour(n)), sty;
styled_loop(l::CurvilinearPolygon, sty::Plain; kwargs...) = l
styled_loop(::CurvilinearPolygon{T}, ::NoRender; kwargs...) where {T} =
CurvilinearPolygon(Point{T}[])
# A lone loop is styled as a single contour, `[1]`, as in `to_polygons`.
styled_loop(l::Union{Polygon, CurvilinearPolygon}, sty::StyleDict; kwargs...) =
styled_loop(l, Polygons._single_contour_style(sty); kwargs...)

# Expand a styled entity into curve-bearing geometry. Entry points accept a bare style
# (single style applied to the whole entity) and dispatch by entity type below.
Expand Down Expand Up @@ -2108,13 +2111,20 @@ end
_carries_curves(e::StyledEntity{T, U}) where {T, U} = _carries_curves(e.ent)

# Entities without a curve-preserving method are discretized.
# Warn once per entity type so the loss is observable.
# Warn once per entity type per context so the loss is observable.
const _curve_loss_warned = Set{Symbol}()
function _maybe_warn_curve_loss(e)
function _maybe_warn_curve_loss(e; context=:recover_curves)
_carries_curves(e) || return nothing
key = Symbol("$(typeof(e))")
key = Symbol(context, " ", typeof(e))
key in _curve_loss_warned && return nothing
push!(_curve_loss_warned, key)
if context === :solidmodel
@warn "Rendering entities of type $(typeof(e)) to an OpenCascade SolidModel " *
"discretizes their curves, because they have no OpenCascade " *
"`SolidModels.to_primitives` method and are rendered via to_polygons. (This " *
"warning is shown once per entity type.)"
return nothing
end
@warn "recover_curves: entities of type $(typeof(e)) have no curve-recovery method " *
"and are discretized via to_polygons — any curves they carry will not be " *
"recovered. (This warning is shown once per entity type.)"
Expand Down
20 changes: 20 additions & 0 deletions src/polygons.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1672,6 +1672,9 @@ Style used for applying differing styles to different Polygons at different leve
`ClippedPolygon` or `CurvilinearRegion`. Styles are stored by the sequence of child indices
required to find the corresponding `Clipper.PolyNode` within the `ClippedPolygon`. For a
`CurvilinearRegion` only dictionaries of depth 2 (a single parent and one set of holes) are valid.

Any other entity, such as a `Rectangle` or a path node, is styled as a single contour with the
style at `[1]` (the default unless set), and styles at other indices throw an `ArgumentError`.
"""
struct StyleDict{S} <: GeometryEntityStyle where {S}
styles::Dict{Vector{Int}, GeometryEntityStyle}
Expand Down Expand Up @@ -1745,6 +1748,23 @@ Base.setindex!(d::StyleDict, s::GeometryEntityStyle, indices::Int...) =
Base.setindex!(d::StyleDict, s::GeometryEntityStyle, n::Clipper.PolyNode) =
addstyle!(d, s, getkey(n))

function _single_contour_style(s::StyleDict)
others = sort!([k for k in keys(s.styles) if k != [1]])
isempty(others) || throw(
ArgumentError(
"this `StyleDict` has styles at $(join(others, ", ")), but only a " *
"`ClippedPolygon` or `CurvilinearRegion` has contours to index. Other entities " *
"are styled as a single contour, `[1]`. To style contours separately, convert " *
"the entity to a `ClippedPolygon` first, for example with `union2d`."
)
)
return s[1]
end

# Without this, the generic fallback hands the polygon straight back to itself.
to_polygons(p::Polygon, s::StyleDict; kwargs...) =
to_polygons(p, _single_contour_style(s); kwargs...)

function to_polygons(p::ClippedPolygon, s::StyleDict; kwargs...)
p = deepcopy(p) # deepcopy so as not to modify
function stylenode!(n::Clipper.PolyNode)
Expand Down
51 changes: 50 additions & 1 deletion src/solidmodels/render.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,31 @@ function to_primitives(::SolidModel, node::Paths.Node, ::Val{true}; kwargs...)
return to_polygons(node; kwargs...)
end

# A style without a SolidModel method of its own is applied through `to_polygons`, as when
# rendering to a `Cell`. That is correct for any style that renders in 2D, at the cost of
# discretizing curves, so warn when curves are lost.
to_primitives(sm::SolidModel, ent::StyledEntity{T, U, S}; kwargs...) where {T, U, S} =
to_primitives(sm, ent.ent; kwargs...)
_apply_style(sm, ent; kwargs...)
function _apply_style(::SolidModel, ent::StyledEntity; kwargs...)
DeviceLayout.Curvilinear._maybe_warn_curve_loss(ent; context=:solidmodel)
return to_polygons(ent; kwargs...)
end
# GmshNative discretizes every curve anyway, so there is nothing to warn about.
_apply_style(::SolidModel{GmshNative}, ent::StyledEntity; kwargs...) =
to_polygons(ent; kwargs...)
# Styles that leave the geometry unchanged pass through, so native curves survive.
to_primitives(
sm::SolidModel,
ent::StyledEntity{T, U, <:Union{Plain, MeshSized, DeviceLayout.WithDirection}};
kwargs...
) where {T, U} = to_primitives(sm, ent.ent; kwargs...)
# `ToTolerance` means rendering the entity with its `atol`, which also keeps native curves.
to_primitives(
sm::SolidModel,
ent::StyledEntity{T, U, <:DeviceLayout.ToTolerance};
kwargs...
) where {T, U} = to_primitives(sm, ent.ent; kwargs..., atol=ent.sty.atol)

function to_primitives(
sm::SolidModel{OpenCascade},
ent::StyledEntity{T, U, S};
Expand All @@ -43,9 +66,29 @@ function to_primitives(
if inner_prim isa Vector
return to_primitives(sm, ent.sty.(inner_prim); kwargs...)
end
# An ellipse has no corners to round, so the kernel's exact ellipse is already the result.
inner_prim isa Ellipse && return inner_prim
# Any other primitive the kernel keeps as is has no rounding method and would come
# straight back here, so round it through `to_curvilinear` instead.
inner_prim === ent.ent &&
return to_primitives(sm, to_curvilinear(inner_prim, ent.sty; kwargs...); kwargs...)
return to_primitives(sm, ent.sty(inner_prim); kwargs...)
end

# An entity without a contour tree is styled as a single contour, `[1]`, as in
# `to_polygons`. Applying that style directly keeps native curves on OpenCascade.
function to_primitives(
sm::SolidModel,
ent::StyledEntity{T, U, <:StyleDict};
kwargs...
) where {T, U}
return to_primitives(
sm,
DeviceLayout.Polygons._single_contour_style(ent.sty)(ent.ent);
kwargs...
)
end

function to_primitives(sm::SolidModel, ent::Vector{<:GeometryEntity}; kwargs...)
return vcat(to_primitives.(sm, ent; kwargs...)...)
end
Expand Down Expand Up @@ -80,6 +123,12 @@ to_primitives(
ent::StyledEntity{T, ClippedPolygon{T}, <:StyleDict};
kwargs...
) where {T} = to_polygons(ent.ent, ent.sty; kwargs...)
# `to_polygons` has no `StyleDict` method for regions, so apply the styles first.
to_primitives(
::SolidModel{GmshNative},
ent::StyledEntity{T, CurvilinearRegion{T}, <:StyleDict};
kwargs...
) where {T} = to_polygons(to_curvilinear(ent.ent, ent.sty; kwargs...); kwargs...)

function to_primitives(::SolidModel, ent::Ellipse; rounded=nothing, Δθ=nothing, kwargs...)
if !isnothing(rounded)
Expand Down
6 changes: 6 additions & 0 deletions src/styles.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ polygons before applying the style.
A style should implement `styled_loop` and `to_curvilinear` methods to allow rounding and curve
recovery with nested styles.

When rendering to an OpenCascade `SolidModel`, a style is applied through `to_polygons`, which
discretizes curves, unless it implements
`SolidModels.to_primitives(::SolidModel{SolidModels.OpenCascade}, ::StyledEntity{T, U, MyStyle}; kwargs...)`
returning curve-bearing geometry such as a `CurvilinearPolygon`. A styled `CurvilinearRegion` is
the exception: it is rendered by applying `styled_loop` to each of its loops.

A style should implement `transform(::MyStyle, f)` if it holds information in a local coordinate
frame (like `WithDirection` does).

Expand Down
8 changes: 8 additions & 0 deletions test/test_shapes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@
rdr = Polygons.Rounded(0.25μm)(rd1)
@test all(isapprox.(all_rounded_render, to_polygons(rdr), atol=0.1nm))
@test bk == rd1 # does not mutate rd1
# On an entity without contours, the StyleDict applies the style of its single contour
@test to_polygons(r1, d) == to_polygons(Polygons.Rounded(0.25μm)(r1))
# and styles at other indices throw rather than being ignored
d2 = StyleDict()
d2[2] = Polygons.Rounded(0.25μm)
cpw = Path(0.0μm, 0.0μm)
straight!(cpw, 10.0μm, Paths.CPW(2.0μm, 1.0μm))
@test_throws ArgumentError to_polygons(d2(cpw[1]))

# Repeat call
all_rounded_render = to_polygons(rd1, d)
Expand Down
116 changes: 116 additions & 0 deletions test/test_solidmodel.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2759,6 +2759,122 @@ end
end
end

@testitem "SolidModel rendering applies entity styles" setup =
[CommonTestSetup, QuietGmshSetup] begin
using DeviceLayout.SolidModels
import DeviceLayout: GeometryEntityStyle, Plain, ToTolerance, WithDirection
import DeviceLayout.SolidModels: to_primitives, GmshNative

# A style that grows its entity, implemented through `to_polygons` as the docs recommend
struct Bias <: GeometryEntityStyle
d::typeof(1.0μm)
end
DeviceLayout.to_polygons(p::Polygon, s::Bias; kwargs...) = only(offset(p, s.d))

sm = SolidModel("styles_occ"; overwrite=true)
smg = SolidModel("styles_native", GmshNative(); overwrite=true)
r = Rectangle(10.0μm, 10.0μm)
c = Circle(5.0μm)
grown = Rectangle(Point(-2.0μm, -2.0μm), Point(12.0μm, 12.0μm))

@testset "Styles without a SolidModel method apply via to_polygons" begin
@test bounds(to_primitives(sm, Bias(2μm)(r))) ≈ grown
@test bounds(to_primitives(smg, Bias(2μm)(r))) ≈ grown
# Rounding on GmshNative
rr = to_primitives(smg, Rounded(2μm)(r))
@test length(points(rr)) > 4
@test Polygons.area(rr) ≈ Polygons.area(to_polygons(Rounded(2μm)(r)))
# Discretizing a curve on OpenCascade warns; GmshNative discretizes everything anyway
empty!(DeviceLayout.Curvilinear._curve_loss_warned)
@test_logs (:warn, r"no OpenCascade `SolidModels.to_primitives` method") to_primitives(
sm,
Bias(1μm)(c)
)
@test_logs to_primitives(smg, Bias(1μm)(c))
end

@testset "ToTolerance renders with its atol" begin
coarse = to_polygons(c; atol=100nm)
@test points(to_primitives(smg, ToTolerance(100nm)(c))) == points(coarse)
@test to_primitives(sm, ToTolerance(100nm)(c)) === c # Native circle kept
end

@testset "Geometry-transparent styles keep native curves" begin
for sty in (Plain(), MeshSized(1μm), WithDirection(0°))
@test to_primitives(sm, sty(c)) === c
@test to_primitives(sm, sty(r)) == to_primitives(sm, r)
end
end

@testset "StyleDict on entities without contours" begin
sd = StyleDict(Rounded(2μm))
reg = to_primitives(sm, sd(to_polygons(r)))
@test reg isa CurvilinearRegion
@test length(reg.exterior.curves) == 4
native = to_primitives(smg, sd(to_polygons(r)))
@test Polygons.area(native) ≈ Polygons.area(to_polygons(Rounded(2μm)(r)))
cp = CurvilinearPolygon(points(r))
@test length(to_primitives(sm, sd(cp)).exterior.curves) == 4
native_reg = to_primitives(smg, sd(CurvilinearRegion(cp)))
@test Polygons.area(only(native_reg)) ≈ Polygons.area(native)
# Other entities: a `Rectangle` keeps exact arcs and a circle stays an exact
# ellipse on OpenCascade; on GmshNative they are rounded via `to_polygons`
@test length(to_primitives(sm, sd(r)).exterior.curves) == 4
@test Polygons.area(to_primitives(smg, sd(r))) ≈ Polygons.area(native)
@test to_primitives(sm, sd(c)) === c
e = Ellipse(Point(0.0μm, 0.0μm), (5.0μm, 3.0μm), 0°)
pa = Path(0.0μm, 0.0μm)
straight!(pa, 10.0μm, Paths.SimpleTrace(2.0μm))
node = pa[1]
empty!(DeviceLayout.Curvilinear._curve_loss_warned)
@test (@test_logs to_primitives(sm, sd(e))) === e
@test (@test_logs to_primitives(sm, sd(node))) isa CurvilinearRegion
for ent in (e, node)
@test (@test_logs to_primitives(smg, sd(ent))) isa Polygon
end
# Styles at other indices have no contour to apply to
sd2 = StyleDict()
sd2[2] = Rounded(1μm)
@test_throws ArgumentError to_primitives(sm, sd2(r))
@test_throws ArgumentError to_primitives(smg, sd2(r))
# Nested inside `Rounded`, which on GmshNative goes through `styled_loop`
twice = to_primitives(smg, Rounded(1μm)(sd(r)))
@test Polygons.area(twice) ≈ Polygons.area(native) rtol = 1e-3
end

@testset "Nested styles" begin
rounded_area = Polygons.area(to_polygons(Rounded(2μm)(r)))
for m in (sm, smg)
for ent in (MeshSized(1μm)(Rounded(2μm)(r)), Rounded(2μm)(MeshSized(1μm)(r)))
@test sum(Polygons.area, vcat(to_polygons(to_primitives(m, ent)))) ≈
rounded_area
end
end
end

@testset "Rounded ellipses stay exact" begin
# An ellipse has no corners, so OpenCascade keeps the native one, without a warning
empty!(DeviceLayout.Curvilinear._curve_loss_warned)
@test (@test_logs to_primitives(sm, Rounded(1μm)(c))) === c
e = Ellipse(Point(0.0μm, 0.0μm), (5.0μm, 3.0μm), 0°)
@test (@test_logs to_primitives(sm, Rounded(1μm)(e))) === e
end

@testset "Styled entities render" begin
cs = CoordinateSystem("styles", nm)
place!(cs, Rounded(2μm)(r), SemanticMeta(:rounded))
place!(cs, Bias(2μm)(r + Point(20μm, 0μm)), SemanticMeta(:biased))
place!(cs, Rounded(1μm)(c + Point(50μm, 0μm)), SemanticMeta(:circle))
for m in (sm, smg)
render!(m, cs; zmap=(_) -> 0μm)
x0, _, _, x1, _, _ = SolidModels.bounds3d(m["biased", 2])
@test x1 - x0 ≈ 14 atol = 1e-3 # μm, grown by 2μm on each side
@test length(SolidModels.get_boundary(m["rounded", 2])) > 4
@test SolidModels.hasgroup(m, "circle", 2)
end
end
end

@testitem "SolidModel verbose rendering through a Schematic" setup =
[CommonTestSetup, QuietGmshSetup] begin
using .SchematicDrivenLayout, Logging
Expand Down
Loading