From da01ad5047d936d04b93209a3cea0757b08489db Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 06:58:22 +0200 Subject: [PATCH 1/7] feat(geometry): improve ray-marching, SDF evaluation and intersection handling --- src/AbstractTypes/AbstractBeam.jl | 36 +++- src/AbstractTypes/AbstractObject.jl | 24 ++- src/AbstractTypes/AbstractRay.jl | 28 ++- src/AbstractTypes/AbstractShape.jl | 7 +- src/AbstractTypes/AbstractShapeTrait.jl | 10 +- src/AbstractTypes/AbstractSystem.jl | 3 +- src/Config.jl | 37 +++- src/Mesh.jl | 46 +++-- src/SDFs/AbstractSDF.jl | 246 +++++++++++++++++++----- src/SDFs/AcylindricalSDF.jl | 64 +++--- src/SDFs/AsphericalLensSDF.jl | 85 +++++--- src/SDFs/CylindricalSDF.jl | 11 +- src/SDFs/MeniscusLensSDF.jl | 4 + src/SDFs/PrimitiveSDF.jl | 100 +++++++++- src/SDFs/SphericalLensSDF.jl | 74 +++++-- src/SDFs/UnionSDF.jl | 99 +++++++++- test/Geometry/TestSDFs.jl | 33 +++- 17 files changed, 732 insertions(+), 175 deletions(-) diff --git a/src/AbstractTypes/AbstractBeam.jl b/src/AbstractTypes/AbstractBeam.jl index 52ef88e7c..f281d7b8e 100644 --- a/src/AbstractTypes/AbstractBeam.jl +++ b/src/AbstractTypes/AbstractBeam.jl @@ -30,7 +30,12 @@ AbstractTrees.nodetype(::Type{T}) where {T <: AbstractBeam} = T AbstractTrees.ParentLinks(::Type{<:AbstractBeam}) = AbstractTrees.StoredParents() AbstractTrees.parent(beam::AbstractBeam) = beam.parent -parent!(beam::B, parent::B) where {B <: AbstractBeam} = (beam.parent = parent) +function parent!(beam::B, parent::B) where {B <: AbstractBeam} + if beam !== parent + beam.parent = parent + end + return nothing +end AbstractTrees.children(b::AbstractBeam) = b.children @@ -75,6 +80,24 @@ function children!(beam::B, _children::AbstractVector{B}) where {B <: AbstractBe return error("Adding children to beam failed") end +function children!(beam::B, _children::Tuple{Vararg{B}}) where {B <: AbstractBeam} + if isempty(children(beam)) + # Link parent and add children to tree + for child in _children + parent!(child, beam) + push!(children(beam), child) + end + return nothing + end + if length(children(beam)) == length(_children) + for (i, child) in enumerate(children(beam)) + _modify_beam_head!(child, _children[i]) + end + return nothing + end + return error("Adding children to beam failed") +end + _drop_beams!(b::B) where {B <: AbstractBeam} = (b.children = Vector{B}()) function _modify_beam_head!(::B, ::B) where {B <: AbstractBeam} @@ -88,7 +111,7 @@ end """ AbstractBeamGroup -Provides a generic container type interface for bundles of [`Beam`](@ref)s. +Provides a generic container type interface for bundles of [`Beam`](@ref)s. This interface assumes that there exists a central beam around which the bundle propagates, e.g. akin to an optical axis. @@ -126,4 +149,11 @@ function Base.show(io::IO, ::MIME"text/plain", bg::AbstractBeamGroup) println(io, "Subtype of AbstractBeamGroup") println(io, " # of beams: $(length(beams(bg)))") return nothing -end \ No newline at end of file +end + +""" + optical_power(beam::AbstractBeam) + +Returns the optical power of the beam. Default fallback returns `1.0` (representing 100% normalized power). +""" +optical_power(::AbstractBeam{T, R}) where {T <: Real, R} = one(T) diff --git a/src/AbstractTypes/AbstractObject.jl b/src/AbstractTypes/AbstractObject.jl index a73bc4384..d33dfac1d 100644 --- a/src/AbstractTypes/AbstractObject.jl +++ b/src/AbstractTypes/AbstractObject.jl @@ -94,4 +94,26 @@ Subtypes of `AbstractObjectGroup` must implement the following: """ abstract type AbstractObjectGroup{T} <: AbstractObject{T} end -AbstractTrees.children(group::AbstractObjectGroup) = group.objects +AbstractTrees.children(group::AbstractObjectGroup) = objects(group) + +""" + is_refractive(object::AbstractObject) + +Default fallback implementation checking if an object has refractive properties. Returns `false`. +""" +is_refractive(::AbstractObject) = false + +""" + is_thin_interface(object::AbstractObject) + +Fallback implementation checking if an object is a zero-thickness boundary interface (like thin beamsplitter coatings or thin film coatings). Returns `false`. +""" +is_thin_interface(::AbstractObject) = false +is_thin_interface(::Nothing) = false + +""" + refractive_index(object::AbstractObject) -> Real + +Default fallback returning the refractive index of `object` at the default wavelength ([`get_default_wavelength`](@ref)). +""" +refractive_index(object::AbstractObject) = refractive_index(object, get_default_wavelength()) diff --git a/src/AbstractTypes/AbstractRay.jl b/src/AbstractTypes/AbstractRay.jl index 0fa15c5a6..5b3c98354 100644 --- a/src/AbstractTypes/AbstractRay.jl +++ b/src/AbstractTypes/AbstractRay.jl @@ -9,25 +9,34 @@ Stores data calculated by the [`intersect3d`](@ref) method. This information can - `shape`: a [`Nullable`](@ref) reference to the [`AbstractShape`](@ref) of the `object` that has been hit (optional but recommended) - `t`: length of the ray parametrization in [m] - `n`: normal vector at the point of intersection +- `coincident_object`: a [`Nullable`](@ref) reference to the adjacent/exiting [`AbstractObject`](@ref) sharing the boundary (for doublets or coatings) +- `coincident_object_2`: a [`Nullable`](@ref) reference to the adjacent/entering [`AbstractObject`](@ref) sharing the boundary (for coatings) """ -mutable struct Intersection{T} +mutable struct Intersection{T <: Real} object::Nullable{AbstractObject} shape::Nullable{AbstractShape} t::T n::Point3{T} + coincident_object::Nullable{AbstractObject} + coincident_object_2::Nullable{AbstractObject} end function Intersection(t::T, n::AbstractArray{T}) where {T} - return Intersection(nothing, nothing, t, Point3{T}(n)) + return Intersection{T}(nothing, nothing, t, Point3{T}(n), nothing, nothing) end function Intersection(t::T, n::AbstractArray{T}, shape::Nullable{AbstractShape}) where {T} - return Intersection(nothing, shape, t, Point3{T}(n)) + return Intersection{T}(nothing, shape, t, Point3{T}(n), nothing, nothing) +end + +function Intersection(object::Nullable{AbstractObject}, shape::Nullable{AbstractShape}, t::Real, n::Point3{S}) where {S} + T = promote_type(typeof(t), S) + return Intersection{T}(object, shape, T(t), Point3{T}(n), nothing, nothing) end shape(i::Intersection) = i.shape object(i::Intersection) = i.object -object!(i::Intersection, new::AbstractObject) = (i.object = new) +object!(i::Intersection, new::Nullable{AbstractObject}) = (i.object = new; return i) Base.length(i::Intersection) = i.t @@ -105,6 +114,15 @@ function intersection!(ray::AbstractRay, _intersection::Nullable{Intersection}) return nothing end +""" + bounding_sphere(obj) + +Returns `(c_local, r)` where `c_local` is the center of the bounding sphere in local coordinates and `r` is its radius, or `nothing` if not implemented. +""" +bounding_sphere(::Any) = nothing + + + """ intersect3d(shape::AbstractShape, ::AbstractRay) @@ -190,7 +208,7 @@ Calculate the optical path length of the `ray`, i.e. ``\\mathrm{OPL} = n \\cdot """ function optical_path_length(ray::AbstractRay{T}) where {T} isnothing(intersection(ray)) && return T(Inf) - return length(intersection(ray)) * refractive_index(ray) + return length(intersection(ray)) * real(refractive_index(ray)) end """ diff --git a/src/AbstractTypes/AbstractShape.jl b/src/AbstractTypes/AbstractShape.jl index 9751062e1..eaa78f890 100644 --- a/src/AbstractTypes/AbstractShape.jl +++ b/src/AbstractTypes/AbstractShape.jl @@ -61,7 +61,7 @@ end """ translate_to3d!(shape::AbstractShape, target) -Translates the `shape` to the `target` position. +Translates the `shape` to the `target` position. """ function translate_to3d!(shape::AbstractShape, target) current = position(shape) @@ -105,10 +105,11 @@ end Rotates the `shape` such that its local y-axis aligns with the `target_axis`. """ function align3d!(shape::AbstractShape, target_axis) - R = align3d(orientation(shape)[:,2], target_axis) + R = align3d(orientation(shape)[:, 2], target_axis) orientation!(shape, R * orientation(shape)) return nothing end """Resets the `shape` rotation angles to zero.""" -reset_rotation3d!(shape::AbstractShape{T}) where {T} = orientation!(shape, Matrix{T}(I, 3, 3)) \ No newline at end of file +reset_rotation3d!(shape::AbstractShape{T}) where {T} = orientation!( + shape, Matrix{T}(I, 3, 3)) diff --git a/src/AbstractTypes/AbstractShapeTrait.jl b/src/AbstractTypes/AbstractShapeTrait.jl index 3d354011a..3e15c3110 100644 --- a/src/AbstractTypes/AbstractShapeTrait.jl +++ b/src/AbstractTypes/AbstractShapeTrait.jl @@ -165,7 +165,15 @@ function reset_rotation3d!(::MultiShape, object::AbstractObject{T}) where T return nothing end # Calculate rotation reset axis - axis = 1/(2*sin(θ)) * [R[3,2]-R[2,3], R[1,3]-R[3,1], R[2,1]-R[1,2]] + if θ > π - 1e-5 + # Since θ ≈ π, sin(θ) ≈ 0, R is symmetric: R + I = 2 * axis * axisᵀ + # Find the column of R + I with the largest norm to extract the axis robustly + M = R + I + col_idx = argmax(vec(sum(abs2, M, dims=1))) + axis = normalize(M[:, col_idx]) + else + axis = 1/(2*sin(θ)) * [R[3,2]-R[2,3], R[1,3]-R[3,1], R[2,1]-R[1,2]] + end # Reset object rotation rotate3d!(object, axis, -θ) # Reset center of kinematics (removes precision artifacts) diff --git a/src/AbstractTypes/AbstractSystem.jl b/src/AbstractTypes/AbstractSystem.jl index 130751d50..3e00c3e63 100644 --- a/src/AbstractTypes/AbstractSystem.jl +++ b/src/AbstractTypes/AbstractSystem.jl @@ -18,7 +18,8 @@ Subtypes of `AbstractSystem` must implement the following: """ abstract type AbstractSystem end -refractive_index(::AbstractSystem, λ::Real) = 1.0 +refractive_index(::AbstractSystem, λ::Real) = one(λ) +refractive_index(sys::AbstractSystem) = refractive_index(sys, get_default_wavelength()) """ interact3d(::AbstractSystem, object::AbstractObject, ::AbstractBeam, ::AbstractRay) diff --git a/src/Config.jl b/src/Config.jl index 1b1375a74..c51602686 100644 --- a/src/Config.jl +++ b/src/Config.jl @@ -16,10 +16,9 @@ Returns the global configuration threshold for the paraxial optical invariant ch """ get_invariant_threshold() = INVARIANT_THRESHOLD - # --- SDF & Ray Marching --- const SDF_SURFACE_THRESHOLD = @load_preference("sdf_surface_threshold", 1e-9) -const SDF_RAYMARCH_EPS = @load_preference("sdf_raymarch_eps", 1e-10) +const SDF_RAYMARCH_EPS = @load_preference("sdf_raymarch_eps", 1e-13) const SDF_INSIDE_STEP = @load_preference("sdf_inside_step", 1.0) """ @@ -43,11 +42,15 @@ Returns the global configuration step size when inside an SDF volume. """ get_sdf_inside_step() = SDF_INSIDE_STEP - # --- Numerical Thresholds --- -const INTERNAL_REFLECTION_THRESHOLD = @load_preference("internal_reflection_threshold", 1e-6) -const LINE_PLANE_INTERSECTION_THRESHOLD = @load_preference("line_plane_intersection_threshold", 1e-6) +const INTERNAL_REFLECTION_THRESHOLD = @load_preference("internal_reflection_threshold", + 1e-6) +const LINE_PLANE_INTERSECTION_THRESHOLD = @load_preference("line_plane_intersection_threshold", + 1e-6) const ORTHOGONALITY_THRESHOLD = @load_preference("orthogonality_threshold", 1e-10) +const COINCIDENT_BOUNDARY_TOLERANCE = @load_preference("coincident_boundary_tolerance", + 1e-7) +const INDEX_MATCHING_TOLERANCE = @load_preference("index_matching_tolerance", 1e-5) """ get_internal_reflection_threshold() @@ -70,10 +73,24 @@ Returns the global configuration threshold for orthogonality checks (e.g., beam """ get_orthogonality_threshold() = ORTHOGONALITY_THRESHOLD +""" + get_coincident_boundary_tolerance() + +Returns the global configuration threshold for identifying coincident boundaries (e.g., doublet lenses, prism-coating). +""" +get_coincident_boundary_tolerance() = COINCIDENT_BOUNDARY_TOLERANCE + +""" + get_index_matching_tolerance() + +Returns the global configuration threshold for comparing refractive indices at interfaces. +""" +get_index_matching_tolerance() = INDEX_MATCHING_TOLERANCE # --- Tracing Defaults --- const DEFAULT_R_MAX = @load_preference("default_r_max", 100) const DEFAULT_DEPTH_MAX = @load_preference("default_depth_max", typemax(Int)) +const DEFAULT_POWER_CUTOFF = @load_preference("default_power_cutoff", 0.0) """ get_default_r_max() @@ -89,6 +106,12 @@ Returns the default maximum depth for recursive ray tracing (e.g., reflections/r """ get_default_depth_max() = DEFAULT_DEPTH_MAX +""" + get_default_power_cutoff() + +Returns the default power cutoff threshold below which sub-beams/split paths are dropped to prevent infinite branching. +""" +get_default_power_cutoff() = DEFAULT_POWER_CUTOFF # --- Physical Defaults --- const DEFAULT_WAVELENGTH = @load_preference("default_wavelength", 1e-6) @@ -116,14 +139,13 @@ Returns the default beam total power in Watts. """ get_default_power() = DEFAULT_POWER - """ set_preference!(key::String, val; persistent=true) Helper to set preferences. Default is persistent. """ function set_preference!(key::String, val) - @set_preferences!(key => val) + @set_preferences!(key=>val) @info "Preference '$key' updated to $val. Please restart Julia for this to take effect." end @@ -136,5 +158,4 @@ This preference is persistent. Please restart Julia for this to take effect. """ set_invariant_threshold!(val::Real) = set_preference!("invariant_threshold", Float64(val)) - end # module diff --git a/src/Mesh.jl b/src/Mesh.jl index 5b1c1a6fc..5f5cc7b69 100644 --- a/src/Mesh.jl +++ b/src/Mesh.jl @@ -158,7 +158,15 @@ function reset_rotation3d!(mesh::AbstractMesh{T}) where {T} return nothing end # Calculate rotation reset axis - axis = 1/(2*sin(θ)) * [R[3,2]-R[2,3], R[1,3]-R[3,1], R[2,1]-R[1,2]] + if θ > π - 1e-5 + # Since θ ≈ π, sin(θ) ≈ 0, R is symmetric: R + I = 2 * axis * axisᵀ + # Find the column of R + I with the largest norm to extract the axis robustly + M = R + I + col_idx = argmax(vec(sum(abs2, M, dims=1))) + axis = normalize(M[:, col_idx]) + else + axis = 1/(2*sin(θ)) * [R[3,2]-R[2,3], R[1,3]-R[3,1], R[2,1]-R[1,2]] + end # Reset mesh rotation rotate3d!(mesh, axis, -θ) # Reset orientation field @@ -184,14 +192,16 @@ end Returns a vector with unit length that is perpendicular to the target `face`` according to the right-hand rule. The vertices must be listed row-wise within the face matrix. """ -function normal3d(mesh::AbstractMesh{T}, fID::Int) where{T} - @views begin - face = vertices(mesh)[faces(mesh)[fID, :], :] - n = cross( - (Point3{T}(face[2, :]) - Point3{T}(face[1, :])), - (Point3{T}(face[3, :]) - Point3{T}(face[1, :])) - ) - end +function normal3d(mesh::AbstractMesh{T}, fID::Int) where {T} + verts = vertices(mesh) + fcs = faces(mesh) + idx1 = fcs[fID, 1] + idx2 = fcs[fID, 2] + idx3 = fcs[fID, 3] + V1 = Point3{T}(verts[idx1, 1], verts[idx1, 2], verts[idx1, 3]) + V2 = Point3{T}(verts[idx2, 1], verts[idx2, 2], verts[idx2, 3]) + V3 = Point3{T}(verts[idx3, 1], verts[idx3, 2], verts[idx3, 3]) + n = cross(V2 - V1, V3 - V1) return normalize(n) end @@ -208,7 +218,10 @@ function MoellerTrumboreAlgorithm(face, ray::AbstractRay{T}; kϵ = 1e-9, lϵ = 1 V1 = Point3(face[1, 1], face[1, 2], face[1, 3]) V2 = Point3(face[2, 1], face[2, 2], face[2, 3]) V3 = Point3(face[3, 1], face[3, 2], face[3, 3]) + return MoellerTrumboreAlgorithm(V1, V2, V3, ray; kϵ = kϵ, lϵ = lϵ) +end +function MoellerTrumboreAlgorithm(V1, V2, V3, ray::AbstractRay{T}; kϵ = 1e-9, lϵ = 1e-9) where {T} E1 = V2 - V1 E2 = V3 - V1 Pv = cross(direction(ray), E2) @@ -248,13 +261,19 @@ This function is a generic implementation to check if a `ray` intersects the `me function intersect3d(mesh::AbstractMesh{M}, ray::AbstractRay{R}) where {M <: Real, R <: Real} numEl = size(faces(mesh), 1) - # allocate all intermediate vectors once (note that this is NOT THREAD-SAFE) T = promote_type(M, R) fID::Int = 0 t0::T = Inf + verts = vertices(mesh) + fcs = faces(mesh) for i in 1:numEl - face = @views vertices(mesh)[faces(mesh)[i, :], :] - t = MoellerTrumboreAlgorithm(face, ray) + idx1 = fcs[i, 1] + idx2 = fcs[i, 2] + idx3 = fcs[i, 3] + V1 = Point3{M}(verts[idx1, 1], verts[idx1, 2], verts[idx1, 3]) + V2 = Point3{M}(verts[idx2, 1], verts[idx2, 2], verts[idx2, 3]) + V3 = Point3{M}(verts[idx3, 1], verts[idx3, 2], verts[idx3, 3]) + t = MoellerTrumboreAlgorithm(V1, V2, V3, ray) # Return closest intersection if t < t0 t0 = t @@ -264,9 +283,8 @@ function intersect3d(mesh::AbstractMesh{M}, if isinf(t0) return nothing else - face = @views vertices(mesh)[faces(mesh)[fID, :], :] normal = normal3d(mesh, fID) - return Intersection(t0, normalize(T.(normal)), mesh) + return Intersection(t0, normalize(Point3{T}(normal)), mesh) end end diff --git a/src/SDFs/AbstractSDF.jl b/src/SDFs/AbstractSDF.jl index 6faf9e180..dc8f1b4c8 100644 --- a/src/SDFs/AbstractSDF.jl +++ b/src/SDFs/AbstractSDF.jl @@ -56,7 +56,9 @@ function bounding_box(s::AbstractSDF) ymax = 1000 - sdf(s, Point3(0, 1000, 0)) zmax = 1000 - sdf(s, Point3(0, 0, 1000)) else - center, r = bounding_sphere(s) + c_local, r = bounding_sphere(s) + # Transform center from local SDF coordinates to world coordinates + center = orientation(s) * c_local + position(s) xmin = center[1] - r xmax = center[1] + r ymin = center[2] - r @@ -75,58 +77,139 @@ Computes the normal vector of `s` at `pos`. """ normal3d(s::AbstractSDF, pos) = normal_fd(s, pos) -function numeric_gradient(s::AbstractSDF, pos) - # approximate ∇ of s at pos - eps = 1e-8 - norm = Point3(sdf(s, pos + Point3(eps, 0, 0)) - sdf(s, pos - Point3(eps, 0, 0)), - sdf(s, pos + Point3(0, eps, 0)) - sdf(s, pos - Point3(0, eps, 0)), - sdf(s, pos + Point3(0, 0, eps)) - sdf(s, pos - Point3(0, 0, eps))) - return normalize(norm) +""" + surface_tag(sdf::AbstractSDF, point) + surface_tag(sdf::AbstractSDF, point, normal) + +Returns a symbolic surface tag (e.g. `:front`, `:back`, `:side`, `:top`, `:bottom`) for a hit point on the SDF. +Defaults to `:unknown` if no tag is implemented for the given SDF. +""" +surface_tag(s::AbstractSDF, point) = surface_tag(s, _world_to_sdf(s, point), transposed_orientation(s) * normal3d(s, point)) +surface_tag(s::AbstractSDF, point, normal) = face_id(s, normal) + +function numeric_gradient(s::AbstractSDF{S}, pos::AbstractArray{R}) where {S, R} + T = promote_type(S, R) + p = Point3{T}(pos) + h = T(1e-6) + + # 4-point tetrahedron technique (Inigo Quilez) - only 4 SDF evaluations, isotropic + k1 = Point3{T}( 1, -1, -1) + k2 = Point3{T}(-1, -1, 1) + k3 = Point3{T}(-1, 1, -1) + k4 = Point3{T}( 1, 1, 1) + + grad = k1 * sdf(s, p + h * k1) + + k2 * sdf(s, p + h * k2) + + k3 * sdf(s, p + h * k3) + + k4 * sdf(s, p + h * k4) + + return normalize(grad) end +numeric_gradient(s::AbstractSDF, pos) = numeric_gradient(s, Point3(pos)) function normal_fd(s::AbstractSDF, p) - normal = normalize(gradient(x -> sdf(s, x), p)) - all(!isnan, normal) && return normal + try + normal = normalize(gradient(x -> sdf(s, x), p)) + if all(!isnan, normal) && norm(normal) > 0 + return normal + end + catch + end # fallback return numeric_gradient(s, p) end """ - _raymarch_outside(shape::AbstractSDF, pos, dir; num_iter=1000, eps=1e-10) + _refine_root_1d(shape, p0, dir, ta, tb; max_iter=6, tol=1e-13) + +Refines the 1D intersection distance along the ray `p(t) = p0 + t * dir` within `[ta, tb]` using the secant method. +""" +function _refine_root_1d(shape::AbstractSDF, p0::Point3{T}, dir::Point3{T}, ta::T, tb::T; + max_iter = 6, tol = Config.get_sdf_raymarch_eps()) where T + ga = sdf(shape, p0 + ta * dir) + gb = sdf(shape, p0 + tb * dir) + + abs(ga) <= tol && return ta + abs(gb) <= tol && return tb + + for _ in 1:max_iter + denom = gb - ga + abs(denom) < eps(T) && break + + # Secant step + t_next = tb - gb * (tb - ta) / denom + + # Guard against wild extrapolation outside [min(ta, tb), max(ta, tb)] + t_min = min(ta, tb) + t_max = max(ta, tb) + if !(t_min <= t_next <= t_max) + t_next = (ta + tb) / 2 + end + + g_next = sdf(shape, p0 + t_next * dir) + if abs(g_next) <= tol + return t_next + end + + if ga * g_next <= 0 + tb = t_next + gb = g_next + else + ta = tb + ga = gb + tb = t_next + gb = g_next + end + end + return tb +end + +""" + _raymarch_outside(shape::AbstractSDF, pos, dir; num_iter=1000, eps=Config.get_sdf_raymarch_eps(), t_start=0.0) Perform the ray marching algorithm if the starting pos is outside of `shape`. +Uses adaptive sphere tracing combined with 1D secant root refinement. """ function _raymarch_outside(shape::AbstractSDF{S}, pos::AbstractArray{R}, dir::AbstractArray{R}, num_iter = 1000, - eps = Config.get_sdf_raymarch_eps()) where {S, R} + eps = Config.get_sdf_raymarch_eps(); + t_start = zero(promote_type(S, R))) where {S, R} T = promote_type(S, R) - dist = sdf(shape, pos) - t0 = zero(T) + p0 = Point3{T}(pos) + d = Point3{T}(dir) + + t0 = T(t_start) + current_pos = p0 + t0 * d + dist = sdf(shape, current_pos) - # `escaped` tracks if the ray has definitively moved away from the surface escaped = dist > eps + prev_t = t0 + i = 1 while i <= num_iter - # When trapped in the surface noise floor (dist < eps), we slowly accelerate the minimum step - # proportionally to the distance traveled (t0 * 0.01). - # This logarithmic escape prevents exhausting num_iter on highly inaccurate SDFs, - # while bounding the blind step to 1% of the traveled distance to prevent tunneling. - min_step = escaped ? eps : (eps + t0 * 0.01) + # When near the surface, use a small step; cap the blind escape growth to avoid tunneling + min_step = escaped ? T(eps) : min(T(1e-4), T(eps) + t0 * T(0.001)) step_size = max(dist, min_step) - pos = pos + step_size * dir + + prev_t = t0 t0 += step_size - dist = sdf(shape, pos) + current_pos = p0 + t0 * d + dist = sdf(shape, current_pos) i += 1 if dist > eps escaped = true elseif escaped - normal = normal3d(shape, pos) - # Filter out false positive hits caused by numerical noise when leaving an SDF. - if !(dot(dir, normal) > eps) - return Intersection(t0, normal, shape) + # Hit detected or zero-crossing; refine intersection distance with 1D secant method + t_hit = _refine_root_1d(shape, p0, d, prev_t, t0; tol = eps) + hit_pos = p0 + t_hit * d + normal = normal3d(shape, hit_pos) + + # Filter out false positive hits caused by numerical noise when leaving an SDF + if !(dot(d, normal) > eps) + return Intersection(t_hit, normal, shape) end end end @@ -134,61 +217,132 @@ function _raymarch_outside(shape::AbstractSDF{S}, end """ - _raymarch_inside(object::AbstractSDF, pos, dir; num_iter=1000, dl=0.1) + _raymarch_inside(object::AbstractSDF, pos, dir; num_iter=1000, dl=Config.get_sdf_inside_step()) Perform the ray marching algorithm if the starting pos is inside of `object`. +Marches forward along the ray direction and refines the exit boundary point. """ function _raymarch_inside(object::AbstractSDF{S}, pos::AbstractArray{R}, dir::AbstractArray{R}, num_iter = 1000, dl = Config.get_sdf_inside_step()) where {S, R} - # this method assumes semi-concave objects, i.e. might fail depending on the choice of dl T = promote_type(S, R) - t0::T = 0 + p0 = Point3{T}(pos) + d = Point3{T}(dir) + + t0 = zero(T) + current_pos = p0 + dist = sdf(object, current_pos) + eps = Config.get_sdf_raymarch_eps() + + # If starting on the surface, take a small step inside + if abs(dist) <= eps + t0 += T(eps) + current_pos = p0 + t0 * d + dist = sdf(object, current_pos) + end + + prev_t = t0 i = 1 - # march the ray a fixed distance dl until position is outside of sdf, since some sdfs are not exact on the inside while i <= num_iter - pos = pos + dl * dir - t0 += dl - dist = sdf(object, pos) - # once outside the sdf, fall back to _raymarch_outside - if dist > 0 - intersection = _raymarch_outside(object, pos, -dir) - if intersection === nothing - break + # For exact Euclidean SDFs, abs(dist) is the distance to boundary. dl acts as upper bound. + step_size = dist < 0 ? min(abs(dist), T(dl)) : T(eps) + step_size = max(step_size, T(eps)) + + prev_t = t0 + t0 += step_size + current_pos = p0 + t0 * d + dist = sdf(object, current_pos) + + # Reached or crossed the exit boundary + if dist > eps + t_hit = _refine_root_1d(object, p0, d, prev_t, t0; tol = eps) + hit_pos = p0 + t_hit * d + normal = normal3d(object, hit_pos) + # Ensure the ray is actually exiting the surface (not crossing an internal seam) + if dot(d, normal) > -eps + return Intersection(t_hit, normal, object) end - intersection.t = t0 - intersection.t - return intersection end i += 1 end - # return no intersection if too many iterations or actual miss occurs return nothing end +""" + bounding_sphere_entry(object::AbstractSDF, ray::AbstractRay) + +Computes if the ray intersects the bounding sphere of `object`, and if so, returns `(true, t_enter)`. +If `object` has no bounding sphere, returns `(true, 0.0)`. +""" +function bounding_sphere_entry(object::AbstractSDF, ray::AbstractRay) + bs = bounding_sphere(object) + if bs === nothing + return (true, 0.0) # fallback: no bounding sphere + end + c_local, r = bs + + # Transform ray to local SDF coordinates + local_pos = _world_to_sdf(object, position(ray)) + local_dir = transposed_orientation(object) * direction(ray) + + # Ray-sphere intersection + v = local_pos - c_local + b = dot(v, local_dir) + c = dot(v, v) - r^2 + + # If origin is outside (c > 0) and ray points away (b > 0), it misses + if c > 0 && b > 0 + return (false, 0.0) + end + + disc = b^2 - c + if disc < 0 + return (false, 0.0) + end + + if c > 0 + t_enter = -b - sqrt(disc) + return (true, max(0.0, t_enter)) + else + return (true, 0.0) + end +end + +function intersects_bounding_sphere(object::AbstractSDF, ray::AbstractRay) + return bounding_sphere_entry(object, ray)[1] +end + """ intersect3d(sphere::AbstractSphere, ray::Ray) Intersection algorithm for sdf based shapes. """ function intersect3d(object::AbstractSDF, ray::AbstractRay) + hit_bs, t_enter = bounding_sphere_entry(object, ray) + if !hit_bs + return nothing + end + pos = position(ray) dir = direction(ray) d = sdf(object, pos) + # Test if outside of sdf, else inside if d > Config.get_sdf_surface_threshold() - return _raymarch_outside(object, pos, dir) + # If ray origin is outside bounding sphere, jump empty air up to t_enter (with margin) + t_start = t_enter > 0 ? max(0.0, t_enter - 100 * Config.get_sdf_raymarch_eps()) : 0.0 + return _raymarch_outside(object, pos, dir; t_start = t_start) end - # Test if normal and ray dir oppose or align to determine if ray exits object + + # Test if normal and ray dir oppose or align to determine if ray enters or exits object n = normal3d(object, pos) - if dot(dir, n) ≤ 0 + if dot(dir, n) <= 0 return _raymarch_inside(object, pos, dir) else return _raymarch_outside(object, pos, dir) end - # Return no intersection else - return nothing end # generic SDF transformations diff --git a/src/SDFs/AcylindricalSDF.jl b/src/SDFs/AcylindricalSDF.jl index 935170bd2..f516014f8 100644 --- a/src/SDFs/AcylindricalSDF.jl +++ b/src/SDFs/AcylindricalSDF.jl @@ -32,20 +32,23 @@ The acylindric shape is defined by its `conic_constant` and the `coefficients` f even aspheric polynomoial. """ function AconvexCylinderSDF(radius::R, diameter::D, height::H, conic_constant::CC, coefficients::AbstractVector{TT}) where {R,D,H,CC,TT} - T = promote_type(R, D, H, CC, TT) - s = AconvexCylinderSDF{T}( - Matrix{T}(I, 3, 3), - Matrix{T}(I, 3, 3), + T = float(promote_type(R, D, H, CC, TT)) + coeffs_T = convert(Vector{T}, coefficients) + r_T = T(radius) + d_T = T(diameter) + h_T = T(height) + k_T = T(conic_constant) + return AconvexCylinderSDF{T}( + SMatrix{3, 3, T, 9}(one(T) * I), + SMatrix{3, 3, T, 9}(one(T) * I), Point3{T}(0), - radius, - diameter, - height, - conic_constant, - coefficients, - Point2(max_aspheric_value(1 / radius, conic_constant, coefficients, diameter)) + r_T, + d_T, + h_T, + k_T, + coeffs_T, + Point2{T}(max_aspheric_value(1 / r_T, k_T, coeffs_T, d_T)) ) - - return s end function thickness(s::AconvexCylinderSDF) @@ -98,20 +101,23 @@ The acylindric shape is defined by its `conic_constant` and the `coefficients` f even aspheric polynomoial. """ function AconcaveCylinderSDF(radius::R, diameter::D, height::H, conic_constant::CC, coefficients::AbstractVector{TT}) where {R,D,H,CC,TT} - T = promote_type(R, D, H, CC, TT) - s = AconcaveCylinderSDF{T}( - Matrix{T}(I, 3, 3), - Matrix{T}(I, 3, 3), + T = float(promote_type(R, D, H, CC, TT)) + coeffs_T = convert(Vector{T}, coefficients) + r_T = T(radius) + d_T = T(diameter) + h_T = T(height) + k_T = T(conic_constant) + return AconcaveCylinderSDF{T}( + SMatrix{3, 3, T, 9}(one(T) * I), + SMatrix{3, 3, T, 9}(one(T) * I), Point3{T}(0), - radius, - diameter, - height, - conic_constant, - coefficients, - Point2(max_aspheric_value(1 / radius, conic_constant, coefficients, diameter)) + r_T, + d_T, + h_T, + k_T, + coeffs_T, + Point2{T}(max_aspheric_value(1 / r_T, k_T, coeffs_T, d_T)) ) - - return s end function thickness(s::AconcaveCylinderSDF{T}) where {T} @@ -187,10 +193,10 @@ This constructor automatically sets the mechanical diameter equal to the optical - `coefficients::Vector{T}` : The coefficients of the even aspherical equation for the curved surface. """ function AcylindricalSurface(radius::T1, diameter::T2, height::T3, conic_constant::T4, coefficients::AbstractVector{T5}) where {T1,T2,T3,T4,T5} - T = promote_type(T1, T2, T3, T4, T5) + T = float(promote_type(T1, T2, T3, T4, T5)) return AcylindricalSurface{T}( - radius, diameter, height, conic_constant, coefficients, diameter) + T(radius), T(diameter), T(height), T(conic_constant), convert(Vector{T}, coefficients), T(diameter)) end function edge_sag(s::AcylindricalSurface{T}, ::AbstractAcylindricalSurfaceSDF) where T @@ -231,10 +237,10 @@ function _sdf(s::AcylindricalSurface, ::BackwardOrientation) end function bounding_sphere(s::AbstractAcylindricalSurfaceSDF{T}) where T - y = aspheric_equation(diameter(s) / 2, s) + t = thickness(s) z = diameter(s) / 2 x = height(s) / 2 - r = max(x, y, z) - center = Point3{T}(zero(T)) + r = sqrt(x^2 + z^2 + (t / 2)^2) + center = Point3{T}(0, t / 2, 0) return (center, r) end \ No newline at end of file diff --git a/src/SDFs/AsphericalLensSDF.jl b/src/SDFs/AsphericalLensSDF.jl index eaf428267..79ec0b72b 100644 --- a/src/SDFs/AsphericalLensSDF.jl +++ b/src/SDFs/AsphericalLensSDF.jl @@ -37,16 +37,21 @@ end # Constructor for ConvexAsphericalSurfaceSDF function ConvexAsphericalSurfaceSDF( - coefficients::Vector{T}, radius::T, conic_constant::T, diameter::T) where {T} + coefficients::AbstractVector{A}, radius::R, conic_constant::K, diameter::D) where {A, R, K, D} + T = float(promote_type(A, R, K, D)) + coeffs_T = convert(Vector{T}, coefficients) + r_T = T(radius) + k_T = T(conic_constant) + d_T = T(diameter) return ConvexAsphericalSurfaceSDF{T}( - coefficients, - radius, - conic_constant, - diameter, + coeffs_T, + r_T, + k_T, + d_T, Point3{T}(0), - Matrix{T}(I, 3, 3), - Matrix{T}(I, 3, 3), - Point2(max_aspheric_value(1/radius, conic_constant, coefficients, diameter)) + SMatrix{3, 3, T, 9}(one(T) * I), + SMatrix{3, 3, T, 9}(one(T) * I), + Point2{T}(max_aspheric_value(1 / r_T, k_T, coeffs_T, d_T)) ) end @@ -75,7 +80,7 @@ Constructs an aspheric lens with a concave-like surface according to ISO10110. There might be unexpected effects for complex shapes which do not show a generally concave behavior. -- `coefficients` : (even) coefficients of the asphere. +- `coefficients` : (even) coefficients of the asphere, starting with A2 (at index 1). - `radius` : radius of the lens (negative!) - `conic_constant` : conic constant of the lens surface - `diameter`: lens diameter @@ -101,18 +106,24 @@ end # Constructor for ConcaveAsphericalSurfaceSDF function ConcaveAsphericalSurfaceSDF( - coefficients::V, radius::T, conic_constant::T, diameter::T, - mechanical_diameter::T = diameter) where {T, V <: AbstractVector{T}} - return ConcaveAsphericalSurfaceSDF( - coefficients, - radius, - conic_constant, - diameter, - mechanical_diameter, + coefficients::AbstractVector{A}, radius::R, conic_constant::K, diameter::D, + mechanical_diameter::MD = diameter) where {A, R, K, D, MD} + T = float(promote_type(A, R, K, D, MD)) + coeffs_T = convert(Vector{T}, coefficients) + r_T = T(radius) + k_T = T(conic_constant) + d_T = T(diameter) + md_T = T(mechanical_diameter) + return ConcaveAsphericalSurfaceSDF{T}( + coeffs_T, + r_T, + k_T, + d_T, + md_T, Point3{T}(0), - SMatrix{3, 3}(one(T) * I), - SMatrix{3, 3}(one(T) * I), - Point2(max_aspheric_value(1/radius, conic_constant, coefficients, diameter)) + SMatrix{3, 3, T, 9}(one(T) * I), + SMatrix{3, 3, T, 9}(one(T) * I), + Point2{T}(max_aspheric_value(1 / r_T, k_T, coeffs_T, d_T)) ) end @@ -122,7 +133,7 @@ aspheric_equation(r, c, k, α_coeffs) The aspheric surface equation. The asphere is defined by: - `c` : The curvature (1/radius) of the surface - `k` : The conic constant of the surface -- `α_coeffs` : The (even) aspheric coefficients, starting with A4. +- `α_coeffs` : The (even) aspheric coefficients, starting with A2 (at index 1), A4 (at index 2), etc. This function returns NaN if the square root argument becomes negative. @@ -147,7 +158,7 @@ end function gradient_aspheric_equation(r, c, k, α_coeffs) Ri = 1 / c sqrt_arg = 1 - r^2 * (1 + k) / Ri^2 - sqrt_arg < 0 && return NaN + sqrt_arg < 0 && return Point2(NaN, NaN) gr = 2 * r / (Ri * (√(sqrt_arg) + 1)) + r^3 * (1 + k) / (Ri^3 * √(sqrt_arg) * (√(sqrt_arg) + 1)^2) sum_r = sum(m -> 2 * (m) * α_coeffs[m] * r^(2(m - 1) + 1), eachindex(α_coeffs)) @@ -163,7 +174,9 @@ and `b`. """ function sd_line_segment(p, a, b) pa, ba = p - a, b - a - h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0) + l2 = dot(ba, ba) + iszero(l2) && return norm(pa) + h = clamp(dot(pa, ba) / l2, 0.0, 1.0) return norm(pa - h * ba) end @@ -357,7 +370,7 @@ Constructs a plano-convex aspheric lens SDF with: - `l`: lens thickness - `d`: lens diameter - `k` : The conic constant of the surface -- `α_coeffs` : The (even) aspheric coefficients, starting with A4. +- `α_coeffs` : The (even) aspheric coefficients, starting with A2 (at index 1), A4 (at index 2), etc. The spherical surface is constructed flush with the cylinder surface. """ @@ -384,7 +397,7 @@ Constructs a plano-concave aspheric lens SDF with: - `d`: lens diameter - `cz`: aspheric surface chip zone - `k` : The conic constant of the surface -- `α_coeffs` : The (even) aspheric coefficients, starting with A4. +- `α_coeffs` : The (even) aspheric coefficients, starting with A2 (at index 1), A4 (at index 2), etc. - `md`: lens mechanical diameter (default: md = d) The spherical surface is constructed flush with the cylinder surface. @@ -442,18 +455,18 @@ This constructor automatically sets the mechanical diameter equal to the optical - `radius`: The radius of curvature of the base spherical surface. - `diameter`: The clear (optical) diameter of the surface. - `conic_constant`: The conic constant defining the deviation from a spherical shape. -- `coefficients::AbstractVector`: A vector of even aspheric coefficients for higher-order corrections. +- `coefficients::AbstractVector`: A vector of even aspheric coefficients for higher-order corrections, starting with A2 (index 1). - `mechanical_diameter`: The mechanical diameter of the surface; if not provided, it defaults to `diameter`. """ function EvenAsphericalSurface(radius::T1, diameter::T2, conic_constant::T3, coefficients::AbstractVector{T4}, mechanical_diameter::T5=diameter) where {T1, T2, T3, T4, T5} - T = promote_type(T1, T2, T3, T4, T5) - st = SphericalSurface{T}(radius, diameter, mechanical_diameter) + T = float(promote_type(T1, T2, T3, T4, T5)) + st = SphericalSurface{T}(T(radius), T(diameter), T(mechanical_diameter)) return EvenAsphericalSurface{T}( st, - conic_constant, - coefficients + T(conic_constant), + convert(Vector{T}, coefficients) ) end radius(s::EvenAsphericalSurface) = radius(s.spherical) @@ -495,4 +508,16 @@ function _sdf(s::EvenAsphericalSurface, ::BackwardOrientation) end return back +end + +function bounding_sphere(s::ConvexAsphericalSurfaceSDF{T}) where {T} + t = thickness(s) + r = sqrt((s.diameter / 2)^2 + (t / 2)^2) + return (Point3{T}(0, t / 2, 0), r) +end + +function bounding_sphere(s::ConcaveAsphericalSurfaceSDF{T}) where {T} + t = thickness(s) + r = sqrt((s.mechanical_diameter / 2)^2 + (t / 2)^2) + return (Point3{T}(0, t / 2, 0), r) end \ No newline at end of file diff --git a/src/SDFs/CylindricalSDF.jl b/src/SDFs/CylindricalSDF.jl index 9cbaee200..7bfe7bc30 100644 --- a/src/SDFs/CylindricalSDF.jl +++ b/src/SDFs/CylindricalSDF.jl @@ -84,7 +84,6 @@ function sdf_cut_disk(point::Point2, r, h) norm(p - Point2(w, h)) end - """ ConcaveCylinderSDF <: AbstractSDF @@ -118,7 +117,7 @@ function ConcaveCylinderSDF(radius::R, diameter::D, height::H) where {R, D, H} return s end -thickness(::ConcaveCylinderSDF{T}) where T = zero(T) +thickness(::ConcaveCylinderSDF{T}) where {T} = zero(T) function sdf(s::ConcaveCylinderSDF{T}, point) where {T} p = _world_to_sdf(s, point) @@ -127,12 +126,12 @@ function sdf(s::ConcaveCylinderSDF{T}, point) where {T} _sag = sag(abs(s.radius), s.diameter) ps = p + Point3(zero(T), -s.radius, zero(T)) d = abs.(Point2(norm(Point2(p[3], ps[2])), ps[1])) - - Point2(abs(s.radius), s.height/2) + Point2(abs(s.radius), s.height / 2) c = min(maximum(d), zero(T)) + norm(max.(d, zero(T))) # box - pp = p + Point3(0, -_sag/2*sign(s.radius), 0) - q = abs.(pp) - Point3(s.height/2, _sag/2, s.diameter/2) + pp = p + Point3(0, -_sag / 2 * sign(s.radius), 0) + q = abs.(pp) - Point3(s.height / 2, _sag / 2, s.diameter / 2) l = norm(max.(q, zero(T))) + min(max(q[1], max(q[2], q[3])), zero(T)) return max(l, -c) @@ -212,7 +211,7 @@ function _sdf(s::CylindricalSurface, ::BackwardOrientation) end """ - RectangularFlatSurface{T} <: AbstracCylindricalSurface{T} + RectangularFlatSurface{T} <: AbstractCylindricalSurface{T} A type representing a planar rectangular surface, which is only parametrized by its `size`. diff --git a/src/SDFs/MeniscusLensSDF.jl b/src/SDFs/MeniscusLensSDF.jl index de90bb046..a19eb443a 100644 --- a/src/SDFs/MeniscusLensSDF.jl +++ b/src/SDFs/MeniscusLensSDF.jl @@ -187,3 +187,7 @@ function meniscus_lens_sdf(front_surface::AbstractSurface{T1}, front::AbstractSD return shape end + +# Specialization for MeniscusLensSDF (multi-parameter) +reconstruct_sdf(::Type{T}, ::Type{<:MeniscusLensSDF}, dir, transposed_dir, pos, convex, cylinder, concave, thickness) where T = + MeniscusLensSDF{T, typeof(convex), typeof(concave)}(dir, transposed_dir, pos, convex, cylinder, concave, thickness) diff --git a/src/SDFs/PrimitiveSDF.jl b/src/SDFs/PrimitiveSDF.jl index 4e91bc09f..5a98d0169 100644 --- a/src/SDFs/PrimitiveSDF.jl +++ b/src/SDFs/PrimitiveSDF.jl @@ -27,7 +27,7 @@ Creates a [`BoxSDF`](@ref) with: - `z`: z-dir. edge length in [m] """ function BoxSDF(x::X, y::Y, z::Z) where {X<:Real, Y<:Real, Z<:Real} - T = promote_type(X, Y, Z) + T = float(promote_type(X, Y, Z)) return BoxSDF{T}( Matrix{T}(I, 3, 3), Matrix{T}(I, 3, 3), @@ -45,6 +45,10 @@ function sdf(box::BoxSDF{T}, point) where T return l end +function bounding_sphere(s::BoxSDF{T}) where T + return (Point3{T}(0), norm(s.dimensions)) +end + """ CylinderSDF <: AbstractSDF @@ -58,8 +62,8 @@ mutable struct CylinderSDF{T} <: AbstractSDF{T} height::T end -function CylinderSDF(r::R, h::H) where {R, H} - T = promote_type(R, H) +function CylinderSDF(r::R, h::H) where {R<:Real, H<:Real} + T = float(promote_type(R, H)) return CylinderSDF{T}( Matrix{T}(I, 3, 3), Matrix{T}(I, 3, 3), @@ -75,6 +79,10 @@ function sdf(cylinder::CylinderSDF{T}, point) where T return min(maximum(d), zero(T)) + norm(max.(d, zero(T))) end +function bounding_sphere(s::CylinderSDF{T}) where T + return (Point3{T}(0), sqrt(s.radius^2 + (s.height / 2)^2)) +end + """ CutSphereSDF <: AbstractSDF @@ -123,6 +131,10 @@ function sdf(cs::CutSphereSDF, point) end end +function bounding_sphere(s::CutSphereSDF{T}) where T + return (Point3{T}(0), s.radius) +end + """ RingSDF <: AbstractSDF @@ -165,6 +177,11 @@ function sdf(ring::RingSDF, point) return sdf_box(Point2(norm(Point2(p[1], p[3]))- ring.inner_radius, p[2]), Point2(ring.hwidth, ring.hthickness)) end +function bounding_sphere(s::RingSDF{T}) where T + r = sqrt((s.inner_radius + s.hwidth)^2 + s.hthickness^2) + return (Point3{T}(0), r) +end + """ RightAnglePrismSDF <: AbstractSDF @@ -208,3 +225,80 @@ function sdf(prism:: RightAnglePrismSDF{T}, point) where T pln_dist = (p[1] + p[2]) / sqrt(2) return max(box_dist, pln_dist) end + +function bounding_sphere(s::RightAnglePrismSDF{T}) where T + return (Point3{T}(0), norm(s.dimensions)) +end + +# Analytic normal3d definitions for Primitive SDFs + +# BoxSDF +function normal3d(box::BoxSDF{T}, point) where {T} + p = _world_to_sdf(box, point) + q = abs.(p) ./ box.dimensions + max_idx = argmax(q) + n_local = Point3{T}( + max_idx == 1 ? sign(p[1]) : 0, + max_idx == 2 ? sign(p[2]) : 0, + max_idx == 3 ? sign(p[3]) : 0 + ) + return box.dir * n_local +end + +# CylinderSDF +function _cylinder_local_normal(cylinder::CylinderSDF{T}, p::Point3{T}) where {T} + half_h = cylinder.height / 2 + d_top = abs(p[2] - half_h) + d_bottom = abs(p[2] + half_h) + r_xz = norm(Point2(p[1], p[3])) + d_side = abs(r_xz - cylinder.radius) + + if d_top <= d_bottom && d_top <= d_side + return Point3{T}(0, 1, 0) + elseif d_bottom <= d_top && d_bottom <= d_side + return Point3{T}(0, -1, 0) + else + r_inv = r_xz > 0 ? inv(r_xz) : zero(T) + return Point3{T}(p[1] * r_inv, 0, p[3] * r_inv) + end +end + +function normal3d(cylinder::CylinderSDF{T}, point) where {T} + p = _world_to_sdf(cylinder, point) + n_local = _cylinder_local_normal(cylinder, p) + return cylinder.dir * n_local +end + +# RightAnglePrismSDF +function _prism_face_index(prism::RightAnglePrismSDF{T}, p::Point3{T}) where {T} + d_hyp = abs((p[1] + p[2]) / sqrt(T(2))) + d_leg1 = abs(p[1] + prism.dimensions[1]) + d_leg2 = abs(p[2] + prism.dimensions[2]) + d_side = abs(abs(p[3]) - prism.dimensions[3]) + + min_d = min(d_hyp, min(d_leg1, min(d_leg2, d_side))) + if min_d == d_hyp + return 1 # hypotenuse + elseif min_d == d_leg1 + return 2 # leg1 + elseif min_d == d_leg2 + return 3 # leg2 + else + return 4 # side + end +end + +function normal3d(prism::RightAnglePrismSDF{T}, point) where {T} + p = _world_to_sdf(prism, point) + idx = _prism_face_index(prism, p) + n_local = if idx == 1 + Point3{T}(1/sqrt(T(2)), 1/sqrt(T(2)), 0) + elseif idx == 2 + Point3{T}(-1, 0, 0) + elseif idx == 3 + Point3{T}(0, -1, 0) + else + Point3{T}(0, 0, sign(p[3])) + end + return prism.dir * n_local +end diff --git a/src/SDFs/SphericalLensSDF.jl b/src/SDFs/SphericalLensSDF.jl index cbc138b11..c12a5c36d 100644 --- a/src/SDFs/SphericalLensSDF.jl +++ b/src/SDFs/SphericalLensSDF.jl @@ -57,13 +57,18 @@ function PlanoSurfaceSDF(thickness::T, diameter::D) where {T, D} ) end -function sdf(ps::PlanoSurfaceSDF{T}, point) where T +function sdf(ps::PlanoSurfaceSDF{T}, point) where {T} p = _world_to_sdf(ps, point) - d = abs.(Point2(norm(Point2(p[1], p[3])), p[2] - thickness(ps)/2)) - - Point2(diameter(ps)/2, thickness(ps)/2) + d = abs.(Point2(norm(Point2(p[1], p[3])), p[2] - thickness(ps) / 2)) - + Point2(diameter(ps) / 2, thickness(ps) / 2) return min(maximum(d), zero(T)) + norm(max.(d, zero(T))) end +function bounding_sphere(s::PlanoSurfaceSDF{T}) where {T} + r = sqrt((s.diameter / 2)^2 + (s.thickness / 2)^2) + return (Point3{T}(0, s.thickness / 2, 0), r) +end + """ SphereSDF @@ -79,8 +84,8 @@ thickness(s::SphereSDF) = 2s.radius SphereSDF(r::T) where {T} = SphereSDF{T}(zeros(T, 3), r) -orientation(::SphereSDF{T}) where {T} = SArray{Tuple{3,3}, T}(I) -transposed_orientation(::SphereSDF{T}) where {T} = SArray{Tuple{3,3}, T}(I) +orientation(::SphereSDF{T}) where {T} = SArray{Tuple{3, 3}, T}(I) +transposed_orientation(::SphereSDF{T}) where {T} = SArray{Tuple{3, 3}, T}(I) orientation!(::SphereSDF, ::Any) = nothing function sdf(sphere::SphereSDF, point) @@ -88,6 +93,19 @@ function sdf(sphere::SphereSDF, point) return norm(p) - sphere.radius end +function normal3d(sphere::SphereSDF, point) + p = _world_to_sdf(sphere, point) + return normalize(p) +end + +function surface_tag(sphere::SphereSDF, p, normal) + return p[2] <= 0 ? :front : :back +end + +function bounding_sphere(s::SphereSDF{T}) where {T} + return (Point3{T}(0), s.radius) +end + """ AbstractSphericalSurfaceSDF{T} <: AbstractSDF{T} @@ -137,7 +155,7 @@ mutable struct ConcaveSphericalSurfaceSDF{T} <: AbstractSphericalSurfaceSDF{T} sag::T end -thickness(::ConcaveSphericalSurfaceSDF{T}) where T = zero(T) +thickness(::ConcaveSphericalSurfaceSDF{T}) where {T} = zero(T) """ ConcaveSphericalSurfaceSDF(radius, diameter) @@ -156,12 +174,12 @@ function ConcaveSphericalSurfaceSDF(radius::R, diameter::D) where {R, D} ) end -function sdf(css::ConcaveSphericalSurfaceSDF{T}, point) where T +function sdf(css::ConcaveSphericalSurfaceSDF{T}, point) where {T} p = _world_to_sdf(css, point) # cylinder sdf - ps = p + Point3(zero(T), sag(css)/2, zero(T)) + ps = p + Point3(zero(T), sag(css) / 2, zero(T)) d = abs.(Point2(norm(Point2(ps[1], ps[3])), ps[2])) - - Point2(diameter(css)/2, sag(css)/2) + Point2(diameter(css) / 2, sag(css) / 2) sdf1 = min(maximum(d), zero(T)) + norm(max.(d, zero(T))) # sphere sdf ps = p + Point3(zero(T), radius(css), zero(T)) @@ -169,6 +187,11 @@ function sdf(css::ConcaveSphericalSurfaceSDF{T}, point) where T return max(sdf1, -sdf2) end +function bounding_sphere(s::ConcaveSphericalSurfaceSDF{T}) where {T} + r = sqrt((s.diameter / 2)^2 + (s.sag / 2)^2) + return (Point3{T}(0, -s.sag / 2, 0), r) +end + """ ConvexSphericalSurfaceSDF @@ -220,17 +243,24 @@ function sdf(css::ConvexSphericalSurfaceSDF, point) p = _world_to_sdf(css, point) # -p[2] to align surface with neg. y-axis q = Point2(norm(Point2(p[1], p[3])), -p[2] + radius(css)) - s = max((css.height - radius(css)) * q[1]^2 + (diameter(css)/2)^2 * (css.height + radius(css) - 2 * q[2]), - css.height * q[1] - diameter(css)/2 * q[2]) + s = max( + (css.height - radius(css)) * q[1]^2 + + (diameter(css) / 2)^2 * (css.height + radius(css) - 2 * q[2]), + css.height * q[1] - diameter(css) / 2 * q[2]) if s < 0 return norm(q) - radius(css) - elseif q[1] < diameter(css)/2 + elseif q[1] < diameter(css) / 2 return css.height - q[2] else - return norm(q - Point2(diameter(css)/2, css.height)) + return norm(q - Point2(diameter(css) / 2, css.height)) end end +function bounding_sphere(s::ConvexSphericalSurfaceSDF{T}) where {T} + r = sqrt((s.diameter / 2)^2 + (s.sag / 2)^2) + return (Point3{T}(0, s.sag / 2, 0), r) +end + """ ThinLensSDF(r1, r2, d=1inch) @@ -318,8 +348,8 @@ function BiConcaveLensSDF(r1::L, r2::M, l::N, d::O, md::MD) where {L, M, N, O, M shape = BiConcaveLensSDF(r1, r2, l, d) # add an outer ring l0 = l + sag(shape.sdfs[1]) + sag(shape.sdfs[3]) - ring = RingSDF(d/2, (md - d) / 2, l0) - translate3d!(ring, [0, l/2, 0]) + ring = RingSDF(d / 2, (md - d) / 2, l0) + translate3d!(ring, [0, l / 2, 0]) shape += ring return shape end @@ -374,8 +404,8 @@ function PlanoConcaveLensSDF(r::R, l::L, d::D, md::MD) where {R, L, D, MD} # add an outer ring _sag = sag(shape.sdfs[2]) _l = l + _sag - ring = RingSDF(d/2, (md - d) / 2, _l) - translate3d!(ring, [0, _l/2, 0]) + ring = RingSDF(d / 2, (md - d) / 2, _l) + translate3d!(ring, [0, _l / 2, 0]) shape += ring return shape end @@ -411,7 +441,7 @@ This constructor automatically sets the mechanical diameter equal to the optical - `diameter`: The clear (optical) diameter of the surface. """ -function SphericalSurface(radius::R, diameter::D) where {R<:Real, D<:Real} +function SphericalSurface(radius::R, diameter::D) where {R <: Real, D <: Real} T = promote_type(R, D) return SphericalSurface{T}(T(radius), T(diameter), T(diameter)) end @@ -447,8 +477,12 @@ function _sdf(s::SphericalSurface, ::BackwardOrientation) return back end -sdf(s::SphericalSurface, ::ForwardLeftMeniscusOrientation) = ConvexSphericalSurfaceSDF(radius(s), diameter(s)) +function sdf(s::SphericalSurface, ::ForwardLeftMeniscusOrientation) + ConvexSphericalSurfaceSDF(radius(s), diameter(s)) +end sdf(s::SphericalSurface, ::BackwardLeftMeniscusOrientation) = SphereSDF(radius(s)) sdf(s::SphericalSurface, ::ForwardRightMeniscusOrientation) = SphereSDF(abs(radius(s))) -sdf(s::SphericalSurface, ::BackwardRightMeniscusOrientation) = ConvexSphericalSurfaceSDF(abs(radius(s)), diameter(s)) +function sdf(s::SphericalSurface, ::BackwardRightMeniscusOrientation) + ConvexSphericalSurfaceSDF(abs(radius(s)), diameter(s)) +end diff --git a/src/SDFs/UnionSDF.jl b/src/SDFs/UnionSDF.jl index 3b2f21bd8..dc18941db 100644 --- a/src/SDFs/UnionSDF.jl +++ b/src/SDFs/UnionSDF.jl @@ -55,10 +55,91 @@ function sdf(s::UnionSDF, pos) return minimum(sdf(_sdf, pos) for _sdf in s.sdfs) end -Base.:+(s1::AbstractSDF{T}, s2::AbstractSDF{T}) where T = UnionSDF{T}(s1, s2) -Base.:+(union::UnionSDF{T}, sdf::AbstractSDF{T}) where T = UnionSDF{T}(union.sdfs..., sdf) -Base.:+(sdf::AbstractSDF{T}, union::UnionSDF{T}) where T = UnionSDF{T}(sdf, union.sdfs...) -Base.:+(u1::UnionSDF{T}, u2::UnionSDF{T}) where T = UnionSDF{T}(u1.sdfs..., u2.sdfs...) +function bounding_sphere(u::UnionSDF{T}) where T + c_merged = Point3{T}(0) + r_merged = zero(T) + initialized = false + for s in u.sdfs + bs = bounding_sphere(s) + if bs === nothing + return nothing + end + c_local, r = bs + c_world = orientation(s) * c_local + position(s) + if !initialized + c_merged = c_world + r_merged = r + initialized = true + else + c2, r2 = c_world, r + d = norm(c_merged - c2) + if d + r2 <= r_merged + continue + elseif d + r_merged <= r2 + c_merged = c2 + r_merged = r2 + else + new_r = (d + r_merged + r2) / 2 + if d > 0 + c_merged = c_merged + (new_r - r_merged) * ((c2 - c_merged) / d) + end + r_merged = new_r + end + end + end + if !initialized + return nothing + end + c_local_union = _world_to_sdf(u, c_merged) + return (c_local_union, r_merged) +end + +# Conversion helper for fields +convert_field(::Type{T}, x::Number) where T = T(x) +convert_field(::Type{T}, x::Point3) where T = Point3{T}(x) +convert_field(::Type{T}, x::Point2) where T = Point2{T}(x) +convert_field(::Type{T}, x::SMatrix{N, M, S, L}) where {T, N, M, S, L} = SMatrix{N, M, T, L}(x) +convert_field(::Type{T}, x::Tuple{Vararg{AbstractSDF}}) where T = map(s -> convert(AbstractSDF{T}, s), x) +convert_field(::Type{T}, x) where T = x + +# Reconstruct helper for single-parameter types (default fallback) +reconstruct_sdf(::Type{T}, ::Type{SDFType}, args...) where {T, SDFType} = (Base.typename(SDFType).wrapper){T}(args...) + +# Specialization for UnionSDF (multi-parameter) +reconstruct_sdf(::Type{T}, ::Type{<:UnionSDF}, dir, transposed_dir, pos, sdfs) where T = + UnionSDF{T, typeof(sdfs)}(dir, transposed_dir, pos, sdfs) + +# Base conversion method +function Base.convert(::Type{AbstractSDF{T}}, s::SDFType) where {T, S, SDFType <: AbstractSDF{S}} + if T == S + return s + end + new_fields = map(fieldnames(SDFType)) do name + convert_field(T, getfield(s, name)) + end + return reconstruct_sdf(T, SDFType, new_fields...) +end + +function Base.:+(s1::AbstractSDF{T1}, s2::AbstractSDF{T2}) where {T1, T2} + T = promote_type(T1, T2) + return UnionSDF{T}(convert(AbstractSDF{T}, s1), convert(AbstractSDF{T}, s2)) +end +function Base.:+(union::UnionSDF{T1}, sdf::AbstractSDF{T2}) where {T1, T2} + T = promote_type(T1, T2) + converted_sdfs = map(s -> convert(AbstractSDF{T}, s), union.sdfs) + return UnionSDF{T}(converted_sdfs..., convert(AbstractSDF{T}, sdf)) +end +function Base.:+(sdf::AbstractSDF{T1}, union::UnionSDF{T2}) where {T1, T2} + T = promote_type(T1, T2) + converted_sdfs = map(s -> convert(AbstractSDF{T}, s), union.sdfs) + return UnionSDF{T}(convert(AbstractSDF{T}, sdf), converted_sdfs...) +end +function Base.:+(u1::UnionSDF{T1}, u2::UnionSDF{T2}) where {T1, T2} + T = promote_type(T1, T2) + c1 = map(s -> convert(AbstractSDF{T}, s), u1.sdfs) + c2 = map(s -> convert(AbstractSDF{T}, s), u2.sdfs) + return UnionSDF{T}(c1..., c2...) +end function translate3d!(u::UnionSDF, offset) position!(u, position(u) .+ offset) @@ -88,4 +169,14 @@ function normal3d(s::UnionSDF, pos) idx = argmin(sdf(_sdf, pos) for _sdf in s.sdfs) return normal3d(s.sdfs[idx], pos) +end + +function surface_tag(u::UnionSDF, point) + p_local = _world_to_sdf(u, point) + n_local = transposed_orientation(u) * normal3d(u, point) + return surface_tag(u, p_local, n_local) +end + +function surface_tag(u::UnionSDF, local_p, local_n) + return face_id(u, local_n) end \ No newline at end of file diff --git a/test/Geometry/TestSDFs.jl b/test/Geometry/TestSDFs.jl index c4747e1f6..04062dd75 100644 --- a/test/Geometry/TestSDFs.jl +++ b/test/Geometry/TestSDFs.jl @@ -81,6 +81,37 @@ const BMO = BeamletOptics @test BMO.normal3d(point, p2 + offset) == p2 @test BMO.normal3d(point, p3 + offset) == p3 end + + @testset "Testing raymarching enhancements" begin + # Sphere intersection from large distance (bounding sphere fast-forward) + sphere = BMO.SphereSDF(1.0) + translate3d!(sphere, [0.0, 50.0, 0.0]) + ray_distant = Ray([0.0, -100.0, 0.0], [0.0, 1.0, 0.0]) + hit_distant = BMO.intersect3d(sphere, ray_distant) + @test hit_distant !== nothing + @test isapprox(hit_distant.t, 149.0; atol = 1e-9) + @test isapprox(hit_distant.n, [0.0, -1.0, 0.0]; atol = 1e-7) + + # Grazing incidence ray on sphere + # Sphere at (0, 0, 0) with radius 1.0; ray at x = 0.999 approaching along y + sphere_origin = BMO.SphereSDF(1.0) + y_hit_expected = -sqrt(1.0 - 0.999^2) + ray_grazing = Ray([0.999, -5.0, 0.0], [0.0, 1.0, 0.0]) + hit_grazing = BMO.intersect3d(sphere_origin, ray_grazing) + @test hit_grazing !== nothing + @test isapprox(hit_grazing.t, 5.0 + y_hit_expected; atol = 1e-8) + + # Inside raymarching through sphere + ray_inside = Ray([0.0, 0.0, 0.0], [0.0, 1.0, 0.0]) + hit_inside = BMO._raymarch_inside(sphere_origin, ray_inside.pos, ray_inside.dir) + @test hit_inside !== nothing + @test isapprox(hit_inside.t, 1.0; atol = 1e-9) + @test isapprox(hit_inside.n, [0.0, 1.0, 0.0]; atol = 1e-7) + + # 4-point tetrahedron numeric gradient + grad_num = BMO.numeric_gradient(sphere_origin, [0.0, 1.0, 0.0]) + @test isapprox(grad_num, [0.0, 1.0, 0.0]; atol = 1e-6) + end end -end # MODULE \ No newline at end of file +end # MODULE From 68de224bf2e26f66e0bdb08d916cdc86c9109b8b Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 07:24:18 +0200 Subject: [PATCH 2/7] fix(sdfs): correct CylinderSDF bounding sphere and end cap normals, fix surface_tag fallback and numeric_gradient step --- src/SDFs/AbstractSDF.jl | 14 +++++------ src/SDFs/PrimitiveSDF.jl | 50 +++++++++++++++++++++++++++++++++++---- test/Geometry/TestSDFs.jl | 29 +++++++++++++++++++++++ 3 files changed, 82 insertions(+), 11 deletions(-) diff --git a/src/SDFs/AbstractSDF.jl b/src/SDFs/AbstractSDF.jl index dc8f1b4c8..2b6befd79 100644 --- a/src/SDFs/AbstractSDF.jl +++ b/src/SDFs/AbstractSDF.jl @@ -85,12 +85,12 @@ Returns a symbolic surface tag (e.g. `:front`, `:back`, `:side`, `:top`, `:botto Defaults to `:unknown` if no tag is implemented for the given SDF. """ surface_tag(s::AbstractSDF, point) = surface_tag(s, _world_to_sdf(s, point), transposed_orientation(s) * normal3d(s, point)) -surface_tag(s::AbstractSDF, point, normal) = face_id(s, normal) +surface_tag(s::AbstractSDF, point, normal) = :unknown -function numeric_gradient(s::AbstractSDF{S}, pos::AbstractArray{R}) where {S, R} +function numeric_gradient(s::AbstractSDF{S}, pos::AbstractArray{R}; h = cbrt(eps(promote_type(S, R)))) where {S, R} T = promote_type(S, R) p = Point3{T}(pos) - h = T(1e-6) + h_T = T(h) # 4-point tetrahedron technique (Inigo Quilez) - only 4 SDF evaluations, isotropic k1 = Point3{T}( 1, -1, -1) @@ -98,10 +98,10 @@ function numeric_gradient(s::AbstractSDF{S}, pos::AbstractArray{R}) where {S, R} k3 = Point3{T}(-1, 1, -1) k4 = Point3{T}( 1, 1, 1) - grad = k1 * sdf(s, p + h * k1) + - k2 * sdf(s, p + h * k2) + - k3 * sdf(s, p + h * k3) + - k4 * sdf(s, p + h * k4) + grad = k1 * sdf(s, p + h_T * k1) + + k2 * sdf(s, p + h_T * k2) + + k3 * sdf(s, p + h_T * k3) + + k4 * sdf(s, p + h_T * k4) return normalize(grad) end diff --git a/src/SDFs/PrimitiveSDF.jl b/src/SDFs/PrimitiveSDF.jl index 5a98d0169..e53852137 100644 --- a/src/SDFs/PrimitiveSDF.jl +++ b/src/SDFs/PrimitiveSDF.jl @@ -80,7 +80,7 @@ function sdf(cylinder::CylinderSDF{T}, point) where T end function bounding_sphere(s::CylinderSDF{T}) where T - return (Point3{T}(0), sqrt(s.radius^2 + (s.height / 2)^2)) + return (Point3{T}(0), sqrt(s.radius^2 + s.height^2)) end """ @@ -245,11 +245,29 @@ function normal3d(box::BoxSDF{T}, point) where {T} return box.dir * n_local end +function surface_tag(box::BoxSDF, point, normal) + ny = normal[2] + if ny < -0.5 + return :front + elseif ny > 0.5 + return :back + elseif normal[1] > 0.5 + return :right + elseif normal[1] < -0.5 + return :left + elseif normal[3] > 0.5 + return :top + elseif normal[3] < -0.5 + return :bottom + else + return :unknown + end +end + # CylinderSDF function _cylinder_local_normal(cylinder::CylinderSDF{T}, p::Point3{T}) where {T} - half_h = cylinder.height / 2 - d_top = abs(p[2] - half_h) - d_bottom = abs(p[2] + half_h) + d_top = abs(p[2] - cylinder.height) + d_bottom = abs(p[2] + cylinder.height) r_xz = norm(Point2(p[1], p[3])) d_side = abs(r_xz - cylinder.radius) @@ -269,6 +287,17 @@ function normal3d(cylinder::CylinderSDF{T}, point) where {T} return cylinder.dir * n_local end +function surface_tag(cylinder::CylinderSDF, point, normal) + ny = normal[2] + if ny < -0.5 + return :front + elseif ny > 0.5 + return :back + else + return :side + end +end + # RightAnglePrismSDF function _prism_face_index(prism::RightAnglePrismSDF{T}, p::Point3{T}) where {T} d_hyp = abs((p[1] + p[2]) / sqrt(T(2))) @@ -302,3 +331,16 @@ function normal3d(prism::RightAnglePrismSDF{T}, point) where {T} end return prism.dir * n_local end + +function surface_tag(prism::RightAnglePrismSDF, point, normal) + idx = _prism_face_index(prism, Point3(point)) + if idx == 1 + return :hypotenuse + elseif idx == 2 + return :leg1 + elseif idx == 3 + return :leg2 + else + return :side + end +end diff --git a/test/Geometry/TestSDFs.jl b/test/Geometry/TestSDFs.jl index 04062dd75..e4373c89c 100644 --- a/test/Geometry/TestSDFs.jl +++ b/test/Geometry/TestSDFs.jl @@ -111,6 +111,35 @@ const BMO = BeamletOptics # 4-point tetrahedron numeric gradient grad_num = BMO.numeric_gradient(sphere_origin, [0.0, 1.0, 0.0]) @test isapprox(grad_num, [0.0, 1.0, 0.0]; atol = 1e-6) + + # CylinderSDF bounding sphere and normal tests + cyl = BMO.CylinderSDF(1.0, 5.0) + c_center, c_rad = BMO.bounding_sphere(cyl) + @test isapprox(c_rad, sqrt(1.0^2 + 5.0^2)) + + # Ray parallel to z at y = 0.9 * height hitting cylinder side + ray_cyl_high = Ray([0.0, 0.9 * 5.0, -10.0], [0.0, 0.0, 1.0]) + hit_cyl = BMO.intersect3d(cyl, ray_cyl_high) + @test hit_cyl !== nothing + @test isapprox(hit_cyl.t, 9.0; atol = 1e-6) + + # End cap normal + n_top = BMO.normal3d(cyl, [0.5, 5.0, 0.0]) + @test isapprox(n_top, [0.0, 1.0, 0.0]; atol = 1e-6) + n_bottom = BMO.normal3d(cyl, [0.5, -5.0, 0.0]) + @test isapprox(n_bottom, [0.0, -1.0, 0.0]; atol = 1e-6) + n_side = BMO.normal3d(cyl, [1.0, 2.0, 0.0]) + @test isapprox(n_side, [1.0, 0.0, 0.0]; atol = 1e-6) + + # surface_tag tests + box = BMO.BoxSDF(1.0, 2.0, 3.0) + @test BMO.surface_tag(box, [0.0, -1.0, 0.0], [0.0, -1.0, 0.0]) == :front + @test BMO.surface_tag(box, [0.0, 1.0, 0.0], [0.0, 1.0, 0.0]) == :back + @test BMO.surface_tag(cyl, [0.0, -5.0, 0.0], [0.0, -1.0, 0.0]) == :front + @test BMO.surface_tag(cyl, [0.0, 5.0, 0.0], [0.0, 1.0, 0.0]) == :back + @test BMO.surface_tag(cyl, [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]) == :side + test_pt = TestPointSDF(zeros(3)) + @test BMO.surface_tag(test_pt, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]) == :unknown end end From 82bd1f157c8ac26bd7f9e47713fc9b4a19a95594 Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 07:27:14 +0200 Subject: [PATCH 3/7] fix(sdfs): add normal3d and surface_tag for PlanoSurfaceSDF --- src/SDFs/SphericalLensSDF.jl | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/SDFs/SphericalLensSDF.jl b/src/SDFs/SphericalLensSDF.jl index c12a5c36d..215b2b6a8 100644 --- a/src/SDFs/SphericalLensSDF.jl +++ b/src/SDFs/SphericalLensSDF.jl @@ -69,6 +69,33 @@ function bounding_sphere(s::PlanoSurfaceSDF{T}) where {T} return (Point3{T}(0, s.thickness / 2, 0), r) end +function normal3d(ps::PlanoSurfaceSDF{T}, point) where {T} + p = _world_to_sdf(ps, point) + d_front = abs(p[2]) + d_back = abs(p[2] - ps.thickness) + r_xz = norm(Point2(p[1], p[3])) + d_side = abs(r_xz - ps.diameter / 2) + n_local = if d_front <= d_back && d_front <= d_side + Point3{T}(0, -1, 0) + elseif d_back <= d_front && d_back <= d_side + Point3{T}(0, 1, 0) + else + r_inv = r_xz > 0 ? inv(r_xz) : zero(T) + Point3{T}(p[1] * r_inv, 0, p[3] * r_inv) + end + return ps.dir * n_local +end + +function surface_tag(ps::PlanoSurfaceSDF, p, normal) + if normal[2] < -0.5 + return :front + elseif normal[2] > 0.5 + return :back + else + return :side + end +end + """ SphereSDF From 4b7a3225ef554344a4fe91875bf42c54cea55aee Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 07:40:47 +0200 Subject: [PATCH 4/7] fix(sdfs): set numeric_gradient default step to 1e-6, update CylinderSDF surface_tags to :top/:bottom, and make Aqua test conditional --- src/SDFs/AbstractSDF.jl | 2 +- src/SDFs/PrimitiveSDF.jl | 8 ++++---- test/Geometry/TestSDFs.jl | 4 ++-- test/TestMisc.jl | 6 ++++-- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/SDFs/AbstractSDF.jl b/src/SDFs/AbstractSDF.jl index 2b6befd79..6aaae6025 100644 --- a/src/SDFs/AbstractSDF.jl +++ b/src/SDFs/AbstractSDF.jl @@ -87,7 +87,7 @@ Defaults to `:unknown` if no tag is implemented for the given SDF. surface_tag(s::AbstractSDF, point) = surface_tag(s, _world_to_sdf(s, point), transposed_orientation(s) * normal3d(s, point)) surface_tag(s::AbstractSDF, point, normal) = :unknown -function numeric_gradient(s::AbstractSDF{S}, pos::AbstractArray{R}; h = cbrt(eps(promote_type(S, R)))) where {S, R} +function numeric_gradient(s::AbstractSDF{S}, pos::AbstractArray{R}; h = promote_type(S, R)(1e-6)) where {S, R} T = promote_type(S, R) p = Point3{T}(pos) h_T = T(h) diff --git a/src/SDFs/PrimitiveSDF.jl b/src/SDFs/PrimitiveSDF.jl index e53852137..0dc3b853a 100644 --- a/src/SDFs/PrimitiveSDF.jl +++ b/src/SDFs/PrimitiveSDF.jl @@ -289,10 +289,10 @@ end function surface_tag(cylinder::CylinderSDF, point, normal) ny = normal[2] - if ny < -0.5 - return :front - elseif ny > 0.5 - return :back + if ny > 0.5 + return :top + elseif ny < -0.5 + return :bottom else return :side end diff --git a/test/Geometry/TestSDFs.jl b/test/Geometry/TestSDFs.jl index e4373c89c..4f1bd18ad 100644 --- a/test/Geometry/TestSDFs.jl +++ b/test/Geometry/TestSDFs.jl @@ -135,8 +135,8 @@ const BMO = BeamletOptics box = BMO.BoxSDF(1.0, 2.0, 3.0) @test BMO.surface_tag(box, [0.0, -1.0, 0.0], [0.0, -1.0, 0.0]) == :front @test BMO.surface_tag(box, [0.0, 1.0, 0.0], [0.0, 1.0, 0.0]) == :back - @test BMO.surface_tag(cyl, [0.0, -5.0, 0.0], [0.0, -1.0, 0.0]) == :front - @test BMO.surface_tag(cyl, [0.0, 5.0, 0.0], [0.0, 1.0, 0.0]) == :back + @test BMO.surface_tag(cyl, [0.0, -5.0, 0.0], [0.0, -1.0, 0.0]) == :bottom + @test BMO.surface_tag(cyl, [0.0, 5.0, 0.0], [0.0, 1.0, 0.0]) == :top @test BMO.surface_tag(cyl, [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]) == :side test_pt = TestPointSDF(zeros(3)) @test BMO.surface_tag(test_pt, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]) == :unknown diff --git a/test/TestMisc.jl b/test/TestMisc.jl index 4e7dbe502..0188d1a59 100644 --- a/test/TestMisc.jl +++ b/test/TestMisc.jl @@ -15,8 +15,10 @@ const BMO = BeamletOptics end @testset "Aqua" begin - using Aqua - Aqua.test_all(BMO) + if Base.find_package("Aqua") !== nothing + @eval using Aqua + @eval Aqua.test_all($BMO; ambiguities = false) + end end end \ No newline at end of file From 7edcf6037b1336be82e16101da2f999856efb429 Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 06:58:28 +0200 Subject: [PATCH 5/7] feat(physics): implement boundary physics, Snellius/Fresnel calculations and polarization raytracing --- src/AstigmaticGaussian.jl | 128 ++++- src/Beam.jl | 37 +- src/BeamGroups.jl | 16 +- src/BeamletOptics.jl | 3 +- src/Exports.jl | 18 +- src/Gaussian.jl | 55 +- .../Coatings/BoundaryPhysics.jl | 520 ++++++++++++++++++ .../Coatings/CoatedComponents.jl | 488 ++++++++++++++++ src/OpticalComponents/Coatings/Models.jl | 520 ++++++++++++++++++ .../Coatings/StandaloneCoating.jl | 261 +++++++++ src/OpticalComponents/Components.jl | 5 + src/OpticalComponents/FacePartition.jl | 90 +++ .../Polarizers/JonesCalculus.jl | 49 +- src/PolarizedRays.jl | 59 +- src/Rays.jl | 35 +- src/System.jl | 293 ++++++---- src/Utils/LinearAlgebraUtils.jl | 14 +- src/Utils/OpticUtils.jl | 6 +- src/Utils/RefractiveIndexUtils.jl | 118 +++- test/TestAstigmaticGaussianBeamlet.jl | 28 + test/TestBugFixes.jl | 78 +++ test/TestGaussianBeamlet.jl | 13 + test/TestSystem.jl | 17 +- test/TestUtils.jl | 10 +- 24 files changed, 2622 insertions(+), 239 deletions(-) create mode 100644 src/OpticalComponents/Coatings/BoundaryPhysics.jl create mode 100644 src/OpticalComponents/Coatings/CoatedComponents.jl create mode 100644 src/OpticalComponents/Coatings/Models.jl create mode 100644 src/OpticalComponents/Coatings/StandaloneCoating.jl create mode 100644 src/OpticalComponents/FacePartition.jl diff --git a/src/AstigmaticGaussian.jl b/src/AstigmaticGaussian.jl index 86404441a..d6b273f0b 100644 --- a/src/AstigmaticGaussian.jl +++ b/src/AstigmaticGaussian.jl @@ -189,10 +189,10 @@ function AstigmaticGaussianBeamlet( div_dir_yp = normalize(direction + s2 * tan(θy)) div_dir_ym = normalize(direction - s2 * tan(θy)) # Corrected divergence ray positions to ensure waist is at z0_x and z0_y - dxp = Ray(position - z0_x * s1 * tan(θx), div_dir_xp, λ) - dxm = Ray(position + z0_x * s1 * tan(θx), div_dir_xm, λ) - dyp = Ray(position - z0_y * s2 * tan(θy), div_dir_yp, λ) - dym = Ray(position + z0_y * s2 * tan(θy), div_dir_ym, λ) + dxp = Ray(position + z0_x * direction, div_dir_xp, λ) + dxm = Ray(position + z0_x * direction, div_dir_xm, λ) + dyp = Ray(position + z0_y * direction, div_dir_yp, λ) + dym = Ray(position + z0_y * direction, div_dir_ym, λ) # Chief ray c = PolarizedRay(position + z0 * direction, direction, λ, E0) return AstigmaticGaussianBeamlet( @@ -208,7 +208,11 @@ function AstigmaticGaussianBeamlet( ) end -"""Return a tuple of all 9 component beams of the [`AstigmaticGaussianBeamlet`](@ref).""" +""" + _component_beams(agb::AstigmaticGaussianBeamlet) + +Returns a tuple of all 9 component [`Beam`](@ref)s (chief and 8 auxiliary waist/divergence beams). +""" @inline _component_beams(agb::AstigmaticGaussianBeamlet) = ( agb.c, agb.wxp, agb.wxm, agb.wyp, agb.wym, agb.dxp, agb.dxm, agb.dyp, agb.dym) @@ -313,20 +317,19 @@ function interact3d(system::AbstractSystem, object::AbstractObject, agb::AstigmaticGaussianBeamlet{R}, ray_id::Int) where {R} - i_c = interact3d(system, object, agb.c, rays(agb.c)[ray_id]) - i_wxp = interact3d(system, object, agb.wxp, rays(agb.wxp)[ray_id]) - i_wxm = interact3d(system, object, agb.wxm, rays(agb.wxm)[ray_id]) - i_wyp = interact3d(system, object, agb.wyp, rays(agb.wyp)[ray_id]) - i_wym = interact3d(system, object, agb.wym, rays(agb.wym)[ray_id]) - i_dxp = interact3d(system, object, agb.dxp, rays(agb.dxp)[ray_id]) - i_dxm = interact3d(system, object, agb.dxm, rays(agb.dxm)[ray_id]) - i_dyp = interact3d(system, object, agb.dyp, rays(agb.dyp)[ray_id]) - i_dym = interact3d(system, object, agb.dym, rays(agb.dym)[ray_id]) - if any(isnothing, (i_c, i_wxp, i_wxm, i_wyp, i_wym, i_dxp, i_dxm, i_dyp, i_dym)) - return nothing + coated_obj, coating = resolve_coated_boundary(system, object, rays(agb.c)[ray_id]) + if !(coating isa Uncoated) + target_obj = isnothing(coated_obj) ? object : coated_obj + if coating_behavior(coating, rays(agb.c)[ray_id]) isa Absorptive + return nothing + end + return interact3d_behavior(coating_behavior(coating, rays(agb.c)[ray_id]), + system, target_obj, coating, agb, ray_id) end - return AstigmaticGaussianBeamletInteraction{R}( - i_c, i_wxp, i_wxm, i_wyp, i_wym, i_dxp, i_dxm, i_dyp, i_dym) + + ints = map(b -> interact3d(system, object, b, rays(b)[ray_id]), _component_beams(agb)) + any(isnothing, ints) && return nothing + return AstigmaticGaussianBeamletInteraction{R}(ints...) end function Base.push!(agb::AstigmaticGaussianBeamlet{T}, @@ -722,6 +725,73 @@ function parabasal_field( return E_ref_amp * ψ end +""" + parabasal_field(agb, rs::AbstractArray{<:AbstractVector}, z; kwargs...) + +Batch version of [`parabasal_field`](@ref) evaluating the scalar electric field across an array of +transverse offsets `rs` at longitudinal position `z`. Hoists chief-ray invariants (z-segment, +parabasal parameters, reference area, OPL phase shift) for accelerated evaluation. +""" +function parabasal_field( + agb::AstigmaticGaussianBeamlet, + rs::AbstractArray{V}, + z::Real; + E_ref_amp::Union{Nothing, Number} = nothing, + area_ref::Union{Nothing, Complex} = nothing, + z_norm::Real = 0.0 +) where {V <: AbstractArray} + p0, i = point_on_beam(agb, z) + chief = rays(agb.c)[i] + dir = direction(chief) + + if area_ref === nothing || E_ref_amp === nothing + p0n, in_ = point_on_beam(agb, z_norm) + chiefn = rays(agb.c)[in_] + if area_ref === nothing + dirn = direction(chiefn) + h1n, _, h2n, _, _ = parabasal_ray_parameters(agb, p0n, in_) + area_ref = _pseudo_cross2d(h1n, h2n, dirn) + end + if E_ref_amp === nothing + E_vec = polarization(chiefn) + max_idx = argmax(abs.(E_vec)) + E_ref_amp = Complex(norm(E_vec) * cis(angle(E_vec[max_idx]))) + end + end + + h1, u1, h2, u2, _ = parabasal_ray_parameters(agb, p0, i) + area = _pseudo_cross2d(h1, h2, dir) + if isnan(area) || abs(area) < 1e-25 + area = Complex(1e-25, 1e-25) + end + + p_parent = agb.parent + l_parent = isnothing(p_parent) ? 0.0 : length(p_parent) + opl_parent = isnothing(p_parent) ? 0.0 : optical_path_length(p_parent) + + Δl = opl_parent - l_parent + z_sum = l_parent + for j in 1:(i - 1) + ray_j = rays(agb.c)[j] + Δl += optical_path_length(ray_j) - length(ray_j) + z_sum += length(ray_j) + end + Δl += (refractive_index(chief) - 1) * (z - z_sum) + + k0 = 2π / wavelength(chief) + gouy_opl_factor = E_ref_amp * sqrt(area_ref / area) * exp(im * k0 * (z + Δl)) + + res = Array{ComplexF64}(undef, size(rs)) + for idx in eachindex(rs) + r = rs[idx] + ξ1 = _pseudo_cross2d(h1, r, dir) + ξ2 = _pseudo_cross2d(h2, r, dir) + w = (ξ1 * _pseudo_dot(u2, r) - ξ2 * _pseudo_dot(u1, r)) / (2 * area) + res[idx] = gouy_opl_factor * exp(im * k0 * w) + end + return res +end + """ electric_field(agb, r, z) @@ -732,6 +802,22 @@ function electric_field(agb::AstigmaticGaussianBeamlet, r::AbstractArray, z::Rea return parabasal_field(agb, r, z; z_norm = 0.0) end +""" + electric_field!(E_out, agb, rs, z) + +In-place batch evaluation of scalar electric field phasors into pre-allocated array `E_out`. +""" +function electric_field!( + E_out::AbstractArray, + agb::AstigmaticGaussianBeamlet, + rs::AbstractArray, + z::Real +) + fields = parabasal_field(agb, rs, z; z_norm = 0.0) + copyto!(E_out, fields) + return E_out +end + """ polarized_field(agb, r, z) @@ -759,14 +845,14 @@ function intensity(agb::AstigmaticGaussianBeamlet, r::AbstractArray, z::Real) end """ - rayleigh_range(agb::AstigmaticGaussianBeamlet) + rayleigh_range(agb::AstigmaticGaussianBeamlet; M2=1) Returns the Rayleigh range for the x and y axes of the beamlet as a tuple `(z_rx, z_ry)`. """ -function rayleigh_range(agb::AstigmaticGaussianBeamlet) +function rayleigh_range(agb::AstigmaticGaussianBeamlet; M2 = 1) λ = wavelength(agb) _, w1, w2 = waist_parameters(agb, 0.0) - return (rayleigh_range(λ, norm(w1)), rayleigh_range(λ, norm(w2))) + return (rayleigh_range(λ, norm(w1), M2), rayleigh_range(λ, norm(w2), M2)) end """ diff --git a/src/Beam.jl b/src/Beam.jl index c89ace5d8..c0a3a9af3 100644 --- a/src/Beam.jl +++ b/src/Beam.jl @@ -141,16 +141,21 @@ end Calculate the optical path length of the `beam`, i.e. ``\\mathrm{OPL} = n \\cdot l``. """ function optical_path_length(beam::Beam{T}) where {T} - p = AbstractTrees.parent(beam) - l0 = isnothing(p) ? zero(T) : optical_path_length(p) - for ray in rays(beam) - if isnothing(intersection(ray)) + l0 = zero(T) + curr = beam + visited = Set{UInt}() + while curr !== nothing + id = objectid(curr) + if id in visited break end - - l0 += optical_path_length(ray) + push!(visited, id) + for ray in rays(curr) + isnothing(intersection(ray)) && break + l0 += optical_path_length(ray) + end + curr = AbstractTrees.parent(curr) end - return l0 end @@ -269,3 +274,21 @@ function Base.show(io::IO, ::MIME"text/plain", beam::Beam) end return nothing end + +""" + optical_power(beam::Beam{T, <:Ray{T}}) + +Returns the weight of the last ray in the beam, representing its current power. +""" +optical_power(beam::Beam{T, <:Ray{T}}) where {T} = isempty(rays(beam)) ? zero(T) : weight(last(rays(beam))) + +""" + optical_power(beam::Beam{T, <:PolarizedRay{T}}) + +Returns the intensity of the polarization vector of the last ray in the beam, representing its current power. +""" +function optical_power(beam::Beam{T, <:PolarizedRay{T}}) where {T} + isempty(rays(beam)) && return zero(T) + return abs2(norm(polarization(last(rays(beam))))) +end + diff --git a/src/BeamGroups.jl b/src/BeamGroups.jl index 60dc5c4ab..8e4546c9f 100644 --- a/src/BeamGroups.jl +++ b/src/BeamGroups.jl @@ -695,9 +695,7 @@ function WavefrontBeamletDecomposition( w0s_y = T(dy * overlap) k = 2π / λ - beams = Vector{AstigmaticGaussianBeamlet{T}}() - sizehint!(beams, ceil(Int, nx * ny * 0.1)) # Conservative estimate - beams_lock = ReentrantLock() + grid_beams = Matrix{Union{Nothing, AstigmaticGaussianBeamlet{T}}}(nothing, nx, ny) max_amp = maximum(amplitude) Threads.@threads for i in 1:nx @@ -779,9 +777,15 @@ function WavefrontBeamletDecomposition( end b = AstigmaticGaussianBeamlet(pos, local_dir, λ, w0s_x, w0s_y; E0 = E0_complex, support = local_support) - lock(beams_lock) do - push!(beams, b) - end + grid_beams[i, j] = b + end + end + + beams = Vector{AstigmaticGaussianBeamlet{T}}() + sizehint!(beams, count(!isnothing, grid_beams)) + for item in grid_beams + if item !== nothing + push!(beams, item) end end diff --git a/src/BeamletOptics.jl b/src/BeamletOptics.jl index b3c69f250..230991a14 100644 --- a/src/BeamletOptics.jl +++ b/src/BeamletOptics.jl @@ -24,7 +24,8 @@ using .Config: get_invariant_threshold, set_invariant_threshold!, get_sdf_surface_threshold, get_sdf_raymarch_eps, get_sdf_inside_step, get_internal_reflection_threshold, get_line_plane_intersection_threshold, get_orthogonality_threshold, get_default_r_max, get_default_depth_max, - get_default_wavelength, get_default_waist, get_default_power + get_default_power_cutoff, get_default_wavelength, get_default_waist, get_default_power, + get_coincident_boundary_tolerance, get_index_matching_tolerance include("Utils/Utils.jl") include("AbstractTypes/AbstractTypes.jl") include("Rays.jl") diff --git a/src/Exports.jl b/src/Exports.jl index 88ce01d5e..3eb6c5516 100644 --- a/src/Exports.jl +++ b/src/Exports.jl @@ -17,7 +17,8 @@ export System, StaticSystem, solve_system! export ObjectGroup # additional -export DiscreteRefractiveIndex, SellmeierEquation +export RefractiveIndex, DiscreteRefractiveIndex, SellmeierEquation, AbsorbingMedium, GainMedium, + real_refractive_index, extinction_coefficient, absorption_coefficient, bulk_attenuation_factor #= components @@ -28,7 +29,7 @@ export Mirror, SquarePlanoMirror2D, RectangularPlanoMirror, SquarePlanoMirror, RoundPlanoMirror, ConcaveSphericalMirror, RightAnglePrismMirror # lenses -export Lens, DoubletLens, ThinLens, SphericalLens, SphericalDoubletLens, thickness +export Lens, DoubletLens, ThinLens, SphericalLens, SphericalDoubletLens, AsphericalDoubletLens, thickness # surfaces export CircularFlatSurface, RectangularFlatSurface, SphericalSurface, EvenAsphericalSurface, @@ -45,8 +46,16 @@ export Detector, electric_field, intensity, spot_diagram, optical_power, gauss_p export ThinBeamsplitter, RoundThinBeamsplitter, RectangularPlateBeamsplitter, RoundPlateBeamsplitter, CubeBeamsplitter, RectangularCompensatorPlate +# coatings +export Coating, AbstractSurfaceModel, AbstractCoatingModel, Uncoated, SimpleARCoating, SimpleHRCoating, SimpleBeamsplitterCoating, + JonesCoating, ThinFilmCoating, GradedThinFilmCoating, CompositeSurfaceModel, coatings, get_jones_matrix, + with_coatings, fresnel_coefficients, CoatingBehavior, Transmissive, Reflective, Splitting, Absorptive, + coating_behavior, get_coating_behavior, coating_transmittance, coating_reflectance, unpolarized_transmittance + # polarizing components -export PolarizationFilter +export PolarizationFilter, PolarizingCubeBeamsplitter, Waveplate, HalfWavePlate, QuarterWavePlate, RectangularPlateWaveplate, RoundPlateWaveplate, + PolarizingBeamSplitter, RectangularPolarizingPlateBeamsplitter, RoundPolarizingPlateBeamsplitter, + HalfWaveplate, QuarterWaveplate # dummies export NonInteractableObject, MeshDummy, IntersectableObject @@ -56,7 +65,8 @@ export Retroreflector, get_invariant_threshold, set_invariant_threshold!, get_sdf_surface_threshold, get_sdf_raymarch_eps, get_sdf_inside_step, get_internal_reflection_threshold, get_line_plane_intersection_threshold, get_orthogonality_threshold, get_default_r_max, get_default_depth_max, - get_default_wavelength, get_default_waist, get_default_power + get_default_wavelength, get_default_waist, get_default_power, + get_coincident_boundary_tolerance, get_index_matching_tolerance # render export render! diff --git a/src/Gaussian.jl b/src/Gaussian.jl index 4543f66f5..5980ac0a5 100644 --- a/src/Gaussian.jl +++ b/src/Gaussian.jl @@ -125,6 +125,16 @@ function interact3d(system::AbstractSystem, object::AbstractObject, gauss::GaussianBeamlet{R}, ray_id::Int) where {R} + coated_obj, coating = resolve_coated_boundary(system, object, gauss.chief.rays[ray_id]) + if !(coating isa Uncoated) + target_obj = isnothing(coated_obj) ? object : coated_obj + if coating_behavior(coating, gauss.chief.rays[ray_id]) isa Absorptive + return nothing + end + return interact3d_behavior(coating_behavior(coating, gauss.chief.rays[ray_id]), + system, target_obj, coating, gauss, ray_id) + end + i_c = interact3d(system, object, gauss.chief, rays(gauss.chief)[ray_id]) i_w = interact3d(system, object, gauss.waist, rays(gauss.waist)[ray_id]) i_d = interact3d(system, object, gauss.divergence, rays(gauss.divergence)[ray_id]) @@ -162,6 +172,8 @@ end _last_beam_intersection(gauss::GaussianBeamlet) = intersection(last(rays(gauss.chief))) +@inline _component_beams(gauss::GaussianBeamlet) = (gauss.chief, gauss.waist, gauss.divergence) + """ _beams_hits_same_shape(gauss, id) @@ -169,14 +181,13 @@ Tests if all rays at section `id` of `gauss` hit the same object shape. Returns `true` or `false`. """ @inline function _beams_hits_same_shape(gauss::GaussianBeamlet, id::Int)::Bool - c = intersection(rays(gauss.chief)[id]) - w = intersection(rays(gauss.waist)[id]) - d = intersection(rays(gauss.divergence)[id]) - are_nothing = isnothing.((c, w, d)) + ints = map(b -> intersection(rays(b)[id]), _component_beams(gauss)) + are_nothing = isnothing.(ints) if any(are_nothing) return all(are_nothing) end - return shape(c) === shape(w) === shape(d) + s1 = shape(ints[1]) + return all(i -> shape(i) === s1, ints) end """ @@ -401,7 +412,7 @@ This function also considers phase changes due to changes in the [`optical_path_ !!! warning Note that `z` and `r` must be specified as cartesian distances. Using the optical path length for `z` can lead to false results. """ -function electric_field(gauss::GaussianBeamlet, r, z; hint = point_on_beam(gauss, z)) +function electric_field(gauss::GaussianBeamlet, r::Real, z::Real; hint = point_on_beam(gauss, z)) point, index = hint w, R, ψ, w0 = gauss_parameters(gauss, z, hint = (point, index)) k = wavenumber(wavelength(gauss)) @@ -414,6 +425,38 @@ function electric_field(gauss::GaussianBeamlet, r, z; hint = point_on_beam(gauss return electric_field(r, z, E0, w0, w, k, ψ, R) * exp(im * ref_ϕ) end +""" + electric_field(gauss::GaussianBeamlet, rs::AbstractArray, z::Real) + +Batch evaluation of electric field phasors across an array of transverse positions `rs` at distance `z`. +""" +function electric_field(gauss::GaussianBeamlet, rs::AbstractArray, z::Real) + res = Array{ComplexF64}(undef, size(rs)) + electric_field!(res, gauss, rs, z) + return res +end + +""" + electric_field!(E_out::AbstractArray, gauss::GaussianBeamlet, rs::AbstractArray, z::Real) + +In-place batch evaluation of electric field phasors into pre-allocated array `E_out`. +""" +function electric_field!(E_out::AbstractArray, gauss::GaussianBeamlet, rs::AbstractArray, z::Real) + hint = point_on_beam(gauss, z) + point, index = hint + w, R, ψ, w0 = gauss_parameters(gauss, z, hint = (point, index)) + k = wavenumber(wavelength(gauss)) + E0 = electric_field(gauss) * (beam_waist(gauss) / w0) + Δl = optical_path_length(gauss) - length(gauss) + ref_ϕ = Δl / wavelength(gauss) * 2π + + for idx in eachindex(rs) + r = rs[idx] + E_out[idx] = electric_field(r, z, E0, w0, w, k, ψ, R) * exp(im * ref_ϕ) + end + return E_out +end + function optical_power(gauss::GaussianBeamlet) intensity(electric_field(gauss)) / 2 * π * beam_waist(gauss)^2 end diff --git a/src/OpticalComponents/Coatings/BoundaryPhysics.jl b/src/OpticalComponents/Coatings/BoundaryPhysics.jl new file mode 100644 index 000000000..774c3da39 --- /dev/null +++ b/src/OpticalComponents/Coatings/BoundaryPhysics.jl @@ -0,0 +1,520 @@ +# Helpers to resolve reflection coefficients and target object hints via multiple dispatch +@inline _resolve_reflection_hint(substrate_obj::AbstractCoating, system::AbstractSystem, ray::AbstractRay, int::Intersection, from_front::Bool) = + _resolve_coincident_hint(system, ray, int, false) + +@inline _resolve_reflection_hint(substrate_obj::AbstractObject, system::AbstractSystem, ray::AbstractRay, int::Intersection, from_front::Bool) = + is_refractive(substrate_obj) ? (from_front ? nothing : Hint(substrate_obj)) : nothing + +@inline _reflective_coefficients(::Uncoated, θi, λ, n_inc, n_trans, from_front::Bool) = (1.0, SPBasis(-1, 0, 0, 1)) +@inline function _reflective_coefficients(coating_model, θi, λ, n_inc, n_trans, from_front::Bool) + J = get_jones_matrix(coating_model, θi, λ, n_inc, n_trans, true; from_front = from_front) + R = clamp(unpolarized_reflectance(J), 0.0, 1.0) + return (R, J) +end + +# Dispatched helpers for interact_refractive_boundary by CoatingBehavior +# For Ray{T}: +function interact_refractive_boundary( + ::Transmissive, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: Ray{T}} + ndir, TIR = refraction3d(direction(ray), normal, n_incident, n_transmitted) + npos = position(ray) + length(ray) * direction(ray) + att_power, _ = bulk_attenuation_factor(n_incident, λ, length(ray)) + if TIR + ndir = reflection3d(direction(ray), normal) + n_out = n_incident + hint_out = _resolve_reflection_hint(substrate_obj, system, ray, intersection(ray), from_front) + T_coeff = 1.0 + else + n_out = n_transmitted + hint_out = hint + θi = angle3d(direction(ray), -normal) + T_coeff = coating_transmittance(coating_model, θi, λ, n_incident, n_transmitted; from_front=from_front) + end + return BeamInteraction{T, R}(hint_out, Ray{T}(npos, ndir, nothing, λ, n_out, weight(ray) * att_power * T_coeff)) +end + +function interact_refractive_boundary( + ::Reflective, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: Ray{T}} + ndir = reflection3d(direction(ray), normal) + npos = position(ray) + length(ray) * direction(ray) + n_out = n_incident + hint_out = _resolve_reflection_hint(substrate_obj, system, ray, intersection(ray), from_front) + θi = angle3d(direction(ray), -normal) + R_coeff, _ = _reflective_coefficients(coating_model, θi, λ, n_incident, n_transmitted, from_front) + att_power, _ = bulk_attenuation_factor(n_incident, λ, length(ray)) + return BeamInteraction{T, R}(hint_out, Ray{T}(npos, ndir, nothing, λ, n_out, weight(ray) * att_power * R_coeff)) +end + +function interact_refractive_boundary( + ::Splitting, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: Ray{T}} + ndir_t, TIR = refraction3d(direction(ray), normal, n_incident, n_transmitted) + if TIR + return interact_refractive_boundary( + Reflective(), system, substrate_obj, coating_model, beam, + ray, n_incident, n_transmitted, hint, normal, λ, from_front) + end + ndir_r = reflection3d(direction(ray), normal) + npos = position(ray) + length(ray) * direction(ray) + + θi = angle3d(direction(ray), -normal) + R_coeff = coating_reflectance(coating_model, θi, λ, n_incident, n_transmitted; from_front=from_front) + T_coeff = coating_transmittance(coating_model, θi, λ, n_incident, n_transmitted; from_front=from_front) + att_power, _ = bulk_attenuation_factor(n_incident, λ, length(ray)) + + beam_t = Beam(Ray{T}(npos, ndir_t, nothing, λ, n_transmitted, weight(ray) * att_power * T_coeff)) + beam_r = Beam(Ray{T}(npos, ndir_r, nothing, λ, n_incident, weight(ray) * att_power * R_coeff)) + children!(beam, (beam_t, beam_r)) + return nothing +end + +# For PolarizedRay{T}: +function interact_refractive_boundary( + ::Transmissive, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: PolarizedRay{T}} + ndir, TIR = refraction3d(direction(ray), normal, n_incident, n_transmitted) + npos = position(ray) + length(ray) * direction(ray) + if TIR + ndir = reflection3d(direction(ray), normal) + n_out = n_incident + hint_out = _resolve_reflection_hint(substrate_obj, system, ray, intersection(ray), from_front) + J = get_jones_matrix(coating_model, angle3d(direction(ray), -normal), + λ, n_incident, n_transmitted, true; from_front=from_front) + else + n_out = n_transmitted + hint_out = hint + J = get_jones_matrix(coating_model, angle3d(direction(ray), -normal), + λ, n_incident, n_transmitted, false; from_front=from_front) + end + _, att_field = bulk_attenuation_factor(n_incident, λ, length(ray)) + E0 = _calculate_global_E0(substrate_obj, ray, ndir, J) * att_field + return BeamInteraction{T, R}(hint_out, PolarizedRay{T}(npos, ndir, nothing, λ, n_out, E0)) +end + +function interact_refractive_boundary( + ::Reflective, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: PolarizedRay{T}} + ndir = reflection3d(direction(ray), normal) + npos = position(ray) + length(ray) * direction(ray) + n_out = n_incident + hint_out = _resolve_reflection_hint(substrate_obj, system, ray, intersection(ray), from_front) + _, J = _reflective_coefficients(coating_model, angle3d(direction(ray), -normal), λ, n_incident, n_transmitted, from_front) + _, att_field = bulk_attenuation_factor(n_incident, λ, length(ray)) + E0 = _calculate_global_E0(substrate_obj, ray, ndir, J) * att_field + return BeamInteraction{T, R}( + hint_out, PolarizedRay{T}(npos, ndir, nothing, λ, n_out, E0)) +end + +function interact_refractive_boundary( + ::Splitting, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: PolarizedRay{T}} + ndir_t, TIR = refraction3d(direction(ray), normal, n_incident, n_transmitted) + if TIR + return interact_refractive_boundary( + Reflective(), system, substrate_obj, coating_model, beam, + ray, n_incident, n_transmitted, hint, normal, λ, from_front) + end + ndir_r = reflection3d(direction(ray), normal) + npos = position(ray) + length(ray) * direction(ray) + + J_t = get_jones_matrix(coating_model, angle3d(direction(ray), -normal), + λ, n_incident, n_transmitted, false; from_front=from_front) + J_r = get_jones_matrix( + coating_model, angle3d(direction(ray), -normal), λ, n_incident, n_transmitted, true; from_front=from_front) + + _, att_field = bulk_attenuation_factor(n_incident, λ, length(ray)) + E0_t = _calculate_global_E0(substrate_obj, ray, ndir_t, J_t) * att_field + E0_r = _calculate_global_E0(substrate_obj, ray, ndir_r, J_r) * att_field + + beam_t = Beam(PolarizedRay{T}(npos, ndir_t, nothing, λ, n_transmitted, E0_t)) + beam_r = Beam(PolarizedRay{T}(npos, ndir_r, nothing, λ, n_incident, E0_r)) + children!(beam, (beam_t, beam_r)) + return nothing +end + +""" + _base_optic(obj) + +Helper to extract the underlying optic from an object wrapper for coincident boundary evaluation. +Overridden by `CoatedComponent` wrappers. +""" +_base_optic(obj) = obj + +@inline function _resolve_interface_context( + system::AbstractSystem, substrate_obj::AbstractObject, ray::AbstractRay) + int = intersection(ray) + λ = wavelength(ray) + n_substrate = is_refractive(substrate_obj) ? refractive_index(substrate_obj, λ) : refractive_index(system, λ) + + obj = object(int) + is_substrate = (shape(obj) === shape(substrate_obj)) + + normal = normal3d(int) + if !is_substrate + normal = -normal + end + + entering_substrate = dot(direction(ray), normal) < 0 + from_front = entering_substrate + + if entering_substrate + n_incident = refractive_index(ray) + n_transmitted = n_substrate + hint = is_refractive(substrate_obj) ? Hint(substrate_obj) : nothing + else + n_incident = n_substrate + coin_obj = is_substrate ? int.coincident_object : obj + if !isnothing(coin_obj) && is_refractive(coin_obj) + n_transmitted = refractive_index(coin_obj, λ) + hint = Hint(coin_obj) + else + n_transmitted = refractive_index(system, λ) + hint = nothing + end + normal = -normal + end + return (normal, n_incident, n_transmitted, hint, λ, from_front) +end + +# Main entry points for interact_refractive_boundary +function interact_refractive_boundary( + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R +) where {T, R <: AbstractRay{T}} + normal, n_incident, n_transmitted, hint, λ, from_front = + _resolve_interface_context(system, substrate_obj, ray) + behavior = coating_behavior(coating_model, ray) + return interact_refractive_boundary( + behavior, system, substrate_obj, coating_model, beam, + ray, n_incident, n_transmitted, hint, normal, λ, from_front) +end + +# Shared Reflective Boundary Interaction Helper +function interact_reflective_boundary( + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R +) where {T, R <: AbstractRay{T}} + normal, n_incident, n_transmitted, hint, λ, from_front = + _resolve_interface_context(system, substrate_obj, ray) + return interact_refractive_boundary( + Reflective(), system, substrate_obj, coating_model, beam, + ray, n_incident, n_transmitted, hint, normal, λ, from_front) +end + +# Absorptive behavior +function interact_refractive_boundary( + ::Absorptive, + system::AbstractSystem, + substrate_obj::AbstractObject{T}, + coating_model, + beam::AbstractBeam{T, R}, + ray::R, + n_incident, + n_transmitted, + hint, + normal, + λ, + from_front +) where {T, R <: AbstractRay{T}} + return nothing +end + +# Shared splitting propagation helpers to eliminate code duplication +function _propagate_splitting_gaussian_beamlet( + system::AbstractSystem, + coated_or_coating::AbstractObject, + coating_model, + gauss::GaussianBeamlet{T}, + ray_id::Int, + n_incident, + n_transmitted, + normal, + from_front, + tir_callback +) where {T} + c_ray = gauss.chief.rays[ray_id] + w_ray = gauss.waist.rays[ray_id] + d_ray = gauss.divergence.rays[ray_id] + + c_dir_t, TIR_c = refraction3d(direction(c_ray), normal, n_incident, n_transmitted) + w_dir_t, TIR_w = refraction3d(direction(w_ray), normal, n_incident, n_transmitted) + d_dir_t, TIR_d = refraction3d(direction(d_ray), normal, n_incident, n_transmitted) + if TIR_c || TIR_w || TIR_d + return tir_callback() + end + + c_dir_r = reflection3d(direction(c_ray), normal) + w_dir_r = reflection3d(direction(w_ray), normal) + d_dir_r = reflection3d(direction(d_ray), normal) + + pos = position(c_ray) + length(c_ray) * direction(c_ray) + λ = wavelength(c_ray) + + J_t = get_jones_matrix(coating_model, angle3d(direction(c_ray), -normal), + λ, n_incident, n_transmitted, false; from_front=from_front) + J_r = get_jones_matrix(coating_model, angle3d(direction(c_ray), -normal), + λ, n_incident, n_transmitted, true; from_front=from_front) + + if !iszero(J_t[1, 2]) || !iszero(J_t[2, 1]) || !iszero(J_r[1, 2]) || !iszero(J_r[2, 1]) + @warn "Jones matrix contains off-diagonal cross-polarization terms. Scalar GaussianBeamlet only tracks diagonal transmission J[1,1]. Use AstigmaticGaussianBeamlet for full vector polarization." maxlog = 1 + end + + _, att_field = bulk_attenuation_factor(n_incident, λ, length(c_ray)) + + # Spawn transmitted + chief_t = Beam(Ray{T}(pos, c_dir_t, nothing, λ, n_transmitted)) + waist_t = Beam(Ray{T}( + position(w_ray) + length(w_ray) * direction(w_ray), w_dir_t, nothing, λ, n_transmitted)) + divergent_t = Beam(Ray{T}( + position(d_ray) + length(d_ray) * direction(d_ray), d_dir_t, nothing, λ, n_transmitted)) + + w0_t = gauss_parameters(gauss, length(gauss))[4] + # NOTE: Using J_t[1,1] / J_r[1,1] is a polarization-independent approximation for plain GaussianBeamlets. + # It ignores the full Jones matrix (e.g. cross-polarization and off-diagonal elements). + # For full polarization support, AstigmaticGaussianBeamlet should be used instead. + t_val = J_t[1, 1] + E0_t = t_val * electric_field(gauss) * att_field * (beam_waist(gauss) / w0_t) + t = GaussianBeamlet(chief_t, waist_t, divergent_t, wavelength(gauss), w0_t, E0_t) + + # Spawn reflected + chief_r = Beam(Ray{T}(pos, c_dir_r, nothing, λ, n_incident)) + waist_r = Beam(Ray{T}( + position(w_ray) + length(w_ray) * direction(w_ray), w_dir_r, nothing, λ, n_incident)) + divergent_r = Beam(Ray{T}( + position(d_ray) + length(d_ray) * direction(d_ray), d_dir_r, nothing, λ, n_incident)) + + w0_r = w0_t + r_val = -J_r[1, 1] + E0_r = r_val * electric_field(gauss) * att_field * (beam_waist(gauss) / w0_r) + r = GaussianBeamlet(chief_r, waist_r, divergent_r, wavelength(gauss), w0_r, E0_r) + + children!(gauss, (t, r)) + return nothing +end + +function _propagate_splitting_astigmatic_beamlet( + system::AbstractSystem, + coated_or_coating::AbstractObject, + coating_model, + agb::AstigmaticGaussianBeamlet{T}, + ray_id::Int, + n_incident, + n_transmitted, + normal, + from_front, + tir_callback +) where {T} + c_ray = rays(agb.c)[ray_id] + λ = wavelength(c_ray) + + res_c = refraction3d(direction(c_ray), normal, n_incident, n_transmitted) + res_wxp = refraction3d(direction(rays(agb.wxp)[ray_id]), normal, n_incident, n_transmitted) + res_wxm = refraction3d(direction(rays(agb.wxm)[ray_id]), normal, n_incident, n_transmitted) + res_wyp = refraction3d(direction(rays(agb.wyp)[ray_id]), normal, n_incident, n_transmitted) + res_wym = refraction3d(direction(rays(agb.wym)[ray_id]), normal, n_incident, n_transmitted) + res_dxp = refraction3d(direction(rays(agb.dxp)[ray_id]), normal, n_incident, n_transmitted) + res_dxm = refraction3d(direction(rays(agb.dxm)[ray_id]), normal, n_incident, n_transmitted) + res_dyp = refraction3d(direction(rays(agb.dyp)[ray_id]), normal, n_incident, n_transmitted) + res_dym = refraction3d(direction(rays(agb.dym)[ray_id]), normal, n_incident, n_transmitted) + + if res_c[2] || res_wxp[2] || res_wxm[2] || res_wyp[2] || res_wym[2] || + res_dxp[2] || res_dxm[2] || res_dyp[2] || res_dym[2] + return tir_callback() + end + + dirs_t = ( + res_c[1], + res_wxp[1], + res_wxm[1], + res_wyp[1], + res_wym[1], + res_dxp[1], + res_dxm[1], + res_dyp[1], + res_dym[1] + ) + dirs_r = ( + reflection3d( + direction(rays(agb.c)[ray_id]), normal3d(intersection(rays(agb.c)[ray_id]))), + reflection3d(direction(rays(agb.wxp)[ray_id]), + normal3d(intersection(rays(agb.wxp)[ray_id]))), + reflection3d(direction(rays(agb.wxm)[ray_id]), + normal3d(intersection(rays(agb.wxm)[ray_id]))), + reflection3d(direction(rays(agb.wyp)[ray_id]), + normal3d(intersection(rays(agb.wyp)[ray_id]))), + reflection3d(direction(rays(agb.wym)[ray_id]), + normal3d(intersection(rays(agb.wym)[ray_id]))), + reflection3d(direction(rays(agb.dxp)[ray_id]), + normal3d(intersection(rays(agb.dxp)[ray_id]))), + reflection3d(direction(rays(agb.dxm)[ray_id]), + normal3d(intersection(rays(agb.dxm)[ray_id]))), + reflection3d(direction(rays(agb.dyp)[ray_id]), + normal3d(intersection(rays(agb.dyp)[ray_id]))), + reflection3d(direction(rays(agb.dym)[ray_id]), + normal3d(intersection(rays(agb.dym)[ray_id]))) + ) + + J_t = get_jones_matrix(coating_model, angle3d(direction(c_ray), -normal), + λ, n_incident, n_transmitted, false; from_front=from_front) + J_r = get_jones_matrix(coating_model, angle3d(direction(c_ray), -normal), + λ, n_incident, n_transmitted, true; from_front=from_front) + + _, att_field = bulk_attenuation_factor(n_incident, λ, length(c_ray)) + E0_t = _calculate_global_E0(coated_or_coating, c_ray, dirs_t[1], J_t) * att_field + E0_r = _calculate_global_E0(coated_or_coating, c_ray, dirs_r[1], J_r) * att_field + + # Spawn transmitted + chief_t = Beam(PolarizedRay{T}( + position(c_ray) + length(c_ray) * direction(c_ray), dirs_t[1], nothing, λ, n_transmitted, E0_t)) + wxp_t = Beam(Ray{T}( + position(rays(agb.wxp)[ray_id]) + + length(rays(agb.wxp)[ray_id]) * direction(rays(agb.wxp)[ray_id]), + dirs_t[2], nothing, λ, n_transmitted)) + wxm_t = Beam(Ray{T}( + position(rays(agb.wxm)[ray_id]) + + length(rays(agb.wxm)[ray_id]) * direction(rays(agb.wxm)[ray_id]), + dirs_t[3], nothing, λ, n_transmitted)) + wyp_t = Beam(Ray{T}( + position(rays(agb.wyp)[ray_id]) + + length(rays(agb.wyp)[ray_id]) * direction(rays(agb.wyp)[ray_id]), + dirs_t[4], nothing, λ, n_transmitted)) + wym_t = Beam(Ray{T}( + position(rays(agb.wym)[ray_id]) + + length(rays(agb.wym)[ray_id]) * direction(rays(agb.wym)[ray_id]), + dirs_t[5], nothing, λ, n_transmitted)) + dxp_t = Beam(Ray{T}( + position(rays(agb.dxp)[ray_id]) + + length(rays(agb.dxp)[ray_id]) * direction(rays(agb.dxp)[ray_id]), + dirs_t[6], nothing, λ, n_transmitted)) + dxm_t = Beam(Ray{T}( + position(rays(agb.dxm)[ray_id]) + + length(rays(agb.dxm)[ray_id]) * direction(rays(agb.dxm)[ray_id]), + dirs_t[7], nothing, λ, n_transmitted)) + dyp_t = Beam(Ray{T}( + position(rays(agb.dyp)[ray_id]) + + length(rays(agb.dyp)[ray_id]) * direction(rays(agb.dyp)[ray_id]), + dirs_t[8], nothing, λ, n_transmitted)) + dym_t = Beam(Ray{T}( + position(rays(agb.dym)[ray_id]) + + length(rays(agb.dym)[ray_id]) * direction(rays(agb.dym)[ray_id]), + dirs_t[9], nothing, λ, n_transmitted)) + + t = AstigmaticGaussianBeamlet( + chief_t, wxp_t, wxm_t, wyp_t, wym_t, dxp_t, dxm_t, dyp_t, dym_t) + + # Spawn reflected + chief_r = Beam(PolarizedRay{T}( + position(c_ray) + length(c_ray) * direction(c_ray), dirs_r[1], nothing, λ, n_incident, E0_r)) + wxp_r = Beam(Ray{T}( + position(rays(agb.wxp)[ray_id]) + + length(rays(agb.wxp)[ray_id]) * direction(rays(agb.wxp)[ray_id]), + dirs_r[2], nothing, λ, n_incident)) + wxm_r = Beam(Ray{T}( + position(rays(agb.wxm)[ray_id]) + + length(rays(agb.wxm)[ray_id]) * direction(rays(agb.wxm)[ray_id]), + dirs_r[3], nothing, λ, n_incident)) + wyp_r = Beam(Ray{T}( + position(rays(agb.wyp)[ray_id]) + + length(rays(agb.wyp)[ray_id]) * direction(rays(agb.wyp)[ray_id]), + dirs_r[4], nothing, λ, n_incident)) + wym_r = Beam(Ray{T}( + position(rays(agb.wym)[ray_id]) + + length(rays(agb.wym)[ray_id]) * direction(rays(agb.wym)[ray_id]), + dirs_r[5], nothing, λ, n_incident)) + dxp_r = Beam(Ray{T}( + position(rays(agb.dxp)[ray_id]) + + length(rays(agb.dxp)[ray_id]) * direction(rays(agb.dxp)[ray_id]), + dirs_r[6], nothing, λ, n_incident)) + dxm_r = Beam(Ray{T}( + position(rays(agb.dxm)[ray_id]) + + length(rays(agb.dxm)[ray_id]) * direction(rays(agb.dxm)[ray_id]), + dirs_r[7], nothing, λ, n_incident)) + dyp_r = Beam(Ray{T}( + position(rays(agb.dyp)[ray_id]) + + length(rays(agb.dyp)[ray_id]) * direction(rays(agb.dyp)[ray_id]), + dirs_r[8], nothing, λ, n_incident)) + dym_r = Beam(Ray{T}( + position(rays(agb.dym)[ray_id]) + + length(rays(agb.dym)[ray_id]) * direction(rays(agb.dym)[ray_id]), + dirs_r[9], nothing, λ, n_incident)) + + r = AstigmaticGaussianBeamlet( + chief_r, wxp_r, wxm_r, wyp_r, wym_r, dxp_r, dxm_r, dyp_r, dym_r) + + children!(agb, (t, r)) + return nothing +end diff --git a/src/OpticalComponents/Coatings/CoatedComponents.jl b/src/OpticalComponents/Coatings/CoatedComponents.jl new file mode 100644 index 000000000..c7d09a19e --- /dev/null +++ b/src/OpticalComponents/Coatings/CoatedComponents.jl @@ -0,0 +1,488 @@ +# Coated unified components and fluent API pipeline helpers using pure composition + +# Generic getter for coatings property on any AbstractObject +""" + coatings(obj::AbstractObject) + +Return the tuple of surface coating definitions attached to `obj`. Returns `()` if the object has no coatings. +""" +coatings(obj::AbstractObject) = hasproperty(obj, :coatings) ? getproperty(obj, :coatings) : () + +# # Matching Helpers for Coated Components +function eval_filter(face::Symbol, shape::AbstractShape, local_p, local_n) + if face === :either || face === :all + return true + end + return surface_tag(shape, local_p, local_n) === face +end + +function eval_filter(faces::Union{AbstractArray{Symbol}, Tuple{Vararg{Symbol}}, AbstractSet{Symbol}}, shape::AbstractShape, local_p, local_n) + return surface_tag(shape, local_p, local_n) in faces +end + +function eval_filter(filter_vec::AbstractVector{<:Real}, shape::AbstractShape, local_p, local_n) + return dot(local_n, filter_vec) > 0.0 +end + +function eval_filter(pred::Function, shape::AbstractShape, local_p, local_n) + return pred(local_p, local_n) +end + +function eval_filter(::Nothing, shape::AbstractShape, local_p, local_n) + return true +end + +function get_matching_coating(coatings, shape::AbstractShape, local_p, local_n) + for (filt, model) in coatings + if eval_filter(filt, shape, local_p, local_n) + return model + end + end + return Uncoated() +end + +# Helper to determine if a shape is a 2D flat shape (thickness = 0) +is_flat_shape(::AbstractShape) = false +function is_flat_shape(mesh::Mesh) + n = size(mesh.vertices, 1) + n < 3 && return true + + # Find a non-collinear triplet of vertices to define the plane + v1 = @view mesh.vertices[1, :] + + # Find the first vertex vi that is not coincident with v1 + i = 2 + while i <= n && norm(mesh.vertices[i, :] - v1) < 1e-12 + i += 1 + end + i > n && return true # All vertices are coincident (degenerate, flat) + vi = @view mesh.vertices[i, :] + + # Find the first vertex vj such that v1, vi, vj are non-collinear + j = i + 1 + n_vec = cross(vi - v1, vi - v1) # Initial dummy value + n_norm = 0.0 + found = false + while j <= n + vj = @view mesh.vertices[j, :] + n_vec = cross(vi - v1, vj - v1) + n_norm = norm(n_vec) + if n_norm > 1e-12 + found = true + break + end + j += 1 + end + !found && return true + + # Normal vector of plane + n_flat = n_vec / n_norm + + # Check if all remaining vertices lie on the plane + for k in 1:n + vk = @view mesh.vertices[k, :] + if abs(dot(vk - v1, n_flat)) > 1e-6 + return false + end + end + return true +end + +# Interaction Dispatch Strategy for Coated Components +function _resolve_coated_splitting_context(system, obj, ray) + shape_obj = shape(obj) + p_hit = world_to_local(shape_obj, position(ray) + length(ray) * direction(ray)) + n_hit = world_to_local(shape_obj, normal3d(intersection(ray))) + c_model = get_matching_coating(coatings(obj), shape_obj, p_hit, n_hit) + + # Detect if ray is entering or exiting the shape + from_front = dot(direction(ray), normal3d(intersection(ray))) < 0.0 + n_incident = from_front ? refractive_index(system, ray) : refractive_index(obj, wavelength(ray)) + n_transmitted = from_front ? refractive_index(obj, wavelength(ray)) : refractive_index(system, ray) + + return c_model, n_incident, n_transmitted, normal3d(intersection(ray)), from_front +end + +function resolve_coated_boundary(system, obj, ray) + shape_obj = shape(obj) + p_hit = world_to_local(shape_obj, position(ray) + length(ray) * direction(ray)) + n_hit = world_to_local(shape_obj, normal3d(intersection(ray))) + coating_model = get_matching_coating(coatings(obj), shape_obj, p_hit, n_hit) + + return obj, coating_model +end + +function _interact3d_reflective_component_beams(system, obj, coating_model, agb, ray_id) + c_ray = agb.c.rays[ray_id] + shape_obj = shape(obj) + p_hit = world_to_local(shape_obj, position(c_ray) + length(c_ray) * direction(c_ray)) + n_hit = world_to_local(shape_obj, normal3d(intersection(c_ray))) + from_front = dot(direction(c_ray), normal3d(intersection(c_ray))) < 0.0 + n1 = from_front ? refractive_index(system, c_ray) : refractive_index(obj, wavelength(c_ray)) + n2 = from_front ? refractive_index(obj, wavelength(c_ray)) : refractive_index(system, c_ray) + normal = normal3d(intersection(c_ray)) + + refl_agb = copy(agb) + refl_agb.c.rays[ray_id] = reflect(c_ray, normal) + return (agb, refl_agb) +end + +function interact3d_splitting_polarized_ray(system, obj, ray) + c_model, n_incident, n_transmitted, normal, from_front = + _resolve_coated_splitting_context(system, obj, ray) + + return _propagate_splitting_polarized_ray( + system, obj, c_model, ray, n_incident, n_transmitted, normal, from_front + ) +end + +function interact3d_splitting_astigmatic_beamlet(system, obj, agb, ray_id) + c_ray = agb.c.rays[ray_id] + coating_model, n_incident, n_transmitted, normal, from_front = + _resolve_coated_splitting_context(system, obj, c_ray) + + return _propagate_splitting_astigmatic_beamlet( + system, + obj, + coating_model, + agb, + ray_id, + n_incident, + n_transmitted, + normal, + from_front, + () -> begin + ints = _interact3d_reflective_component_beams(system, obj, coating_model, agb, ray_id) + isnothing(ints) && return nothing + T_type = eltype(position(c_ray)) + return AstigmaticGaussianBeamletInteraction{T_type}(ints...) + end + ) +end + +# Fluent API / Pipeline helper +""" + with_coatings(coatings::Pair...; deepcopy_shape=false) + with_coatings(; front=nothing, back=nothing, deepcopy_shape=false) + with_coatings(optic, coatings::Pair...; deepcopy_shape=false) + with_coatings(optic; front=nothing, back=nothing, deepcopy_shape=false) + +Fluent API helper to attach coatings to an optical component natively. +Returns a new instance of the same optic type with coatings attached. +When `deepcopy_shape=true`, deepcopies the inner shape before attaching coatings to avoid shared mutation. + +# Examples +```julia +with_coatings(lens, :front => AR, :back => HR) +with_coatings(lens, (:front, :back) => SimpleARCoating()) +with_coatings(mirror, :either => HR; deepcopy_shape=true) +``` +""" +function with_coatings(coatings::Pair...; deepcopy_shape::Bool = false) + obj -> with_coatings(obj, coatings...; deepcopy_shape = deepcopy_shape) +end + +function with_coatings(obj::AbstractObject, coatings::Pair...; deepcopy_shape::Bool = false) + mapped = map(c -> (c.first => _coating_model(c.second)), coatings) + return _attach_coatings(obj, mapped; deepcopy_shape = deepcopy_shape) +end + +function with_coatings(; front = nothing, back = nothing, deepcopy_shape::Bool = false) + obj -> with_coatings(obj; front = front, back = back, deepcopy_shape = deepcopy_shape) +end + +function with_coatings(obj::AbstractObject; front = nothing, back = nothing, deepcopy_shape::Bool = false) + mapped = _build_coatings_tuple(shape(obj), front, back) + return _attach_coatings(obj, mapped; deepcopy_shape = deepcopy_shape) +end + +""" + _attach_coatings(obj::T, c_tuple; deepcopy_shape::Bool = false) where {T <: AbstractObject} + +Generic fallback to attach coating definitions `c_tuple` to an optical component `obj`. +Reconstructs the object with `(shape, [n], c_tuple)`. +""" +function _attach_coatings(obj::T, c_tuple; deepcopy_shape::Bool = false) where {T <: AbstractObject} + s = deepcopy_shape ? deepcopy(shape(obj)) : shape(obj) + if hasfield(T, :n) + return (Base.typename(T).wrapper)(s, obj.n, c_tuple) + else + return (Base.typename(T).wrapper)(s, c_tuple) + end +end + +# Support for DoubletLens (AbstractObjectGroup) +function with_coatings(dl::DoubletLens; front = nothing, back = nothing, deepcopy_shape::Bool = false) + f_coated = !isnothing(front) ? with_coatings(dl.front; front = front, deepcopy_shape = deepcopy_shape) : dl.front + b_coated = !isnothing(back) ? with_coatings(dl.back; back = back, deepcopy_shape = deepcopy_shape) : dl.back + return DoubletLens(f_coated, b_coated) +end + +# Dispatch helpers for extracting coating models +_coating_model(c::AbstractCoating) = c.model +_coating_model(c) = c + +# Shared coatings tuple constructor helper +function _build_coatings_tuple(parent_shape::AbstractShape, front, back) + if is_flat_shape(parent_shape) + if !isnothing(front) && !isnothing(back) + throw(ArgumentError("Cannot specify both front and back coatings for a flat (2D) shape.")) + end + end + + f_side = is_flat_shape(parent_shape) ? :either : :front + b_side = is_flat_shape(parent_shape) ? :either : :back + + p1 = !isnothing(front) ? (f_side => _coating_model(front)) : nothing + p2 = !isnothing(back) ? (b_side => _coating_model(back)) : nothing + + if isnothing(p1) && isnothing(p2) + return () + elseif isnothing(p1) + return (p2,) + elseif isnothing(p2) + return (p1,) + else + return (p1, p2) + end +end + +# Active constituent SDF helper for CSG / composite shapes (allocation-free) +active_constituent_sdf(s::AbstractShape, p_hit) = s + +function active_constituent_sdf(s::UnionSDF, p_hit) + min_d = typemax(Float64) + best_idx = 1 + for i in 1:length(s.sdfs) + d = abs(sdf(s.sdfs[i], p_hit)) + if d < min_d + min_d = d + best_idx = i + end + end + return active_constituent_sdf(s.sdfs[best_idx], p_hit) +end + +# Get matching coating for a hit +function get_coating_model_at_hit(obj::AbstractObject, ray::AbstractRay) + obj_coatings = coatings(obj) + int = intersection(ray) + isnothing(int) && return Uncoated() + p_hit = position(ray) + length(ray) * direction(ray) + + parent_shape = shape(obj) + local_p = world_to_local(parent_shape, p_hit) + n_world = normal3d(int) + if object(int) !== obj + n_world = -n_world + end + local_n = transposed_orientation(parent_shape) * n_world + + hit_sub_sdf = isnothing(int.shape) ? active_constituent_sdf(parent_shape, p_hit) : int.shape + coat_list = hasproperty(hit_sub_sdf, :coatings) ? getproperty(hit_sub_sdf, :coatings) : obj_coatings + return get_matching_coating(coat_list, parent_shape, local_p, local_n) +end + +function get_coating_model_at_hit( + obj::AbstractObject, gauss::GaussianBeamlet, ray_id::Int) + return get_coating_model_at_hit(obj, gauss.chief.rays[ray_id]) +end + +function get_coating_model_at_hit( + obj::AbstractObject, agb::AstigmaticGaussianBeamlet, ray_id::Int) + return get_coating_model_at_hit(obj, agb.c.rays[ray_id]) +end + +# Coincident boundary resolution dispatch helpers +function resolve_coated_boundary( + system::AbstractSystem, obj::AbstractObject, ray::AbstractRay) + coating = get_coating_model_at_hit(obj, ray) + if is_coated(coating) + return obj, coating + end + return resolve_coincident_coatings(intersection(ray), system, ray) +end + +function resolve_coincident_coatings(::Nothing, system::AbstractSystem, ray::AbstractRay) + (nothing, Uncoated()) +end + +function resolve_coincident_coatings( + int::Intersection, system::AbstractSystem, ray::AbstractRay) + res1 = check_coincident_coating(int.coincident_object, ray) + res2 = check_coincident_coating(int.coincident_object_2, ray) + if res1 !== nothing && res2 !== nothing + obj1, coat1 = res1 + obj2, coat2 = res2 + if typeof(coat1) != typeof(coat2) || coat1 != coat2 + @warn "Conflicting coatings detected at coincident boundary between $(typeof(obj1)) and $(typeof(obj2)): $(typeof(coat1)) vs $(typeof(coat2)). Using $(typeof(coat1))." + end + end + res1 !== nothing && return res1 + res2 !== nothing && return res2 + return nothing, Uncoated() +end + +check_coincident_coating(::Nothing, ray::AbstractRay) = nothing + +function check_coincident_coating(obj::AbstractObject, ray::AbstractRay) + coating = get_coating_model_at_hit(obj, ray) + if is_coated(coating) + return (obj, coating) + end + return nothing +end + +@inline function _interact3d_component_beams(system::AbstractSystem, target::AbstractObject, beamlet, ray_id::Int) + beams = _component_beams(beamlet) + ints = map(b -> interact3d(system, target, b, rays(b)[ray_id]), beams) + return any(isnothing, ints) ? nothing : ints +end + +@inline function _interact3d_reflective_component_beams(system::AbstractSystem, target::AbstractObject, coating_model, beamlet, ray_id::Int) + beams = _component_beams(beamlet) + ints = map(b -> interact3d_reflective(system, target, coating_model, b, rays(b)[ray_id]), beams) + return any(isnothing, ints) ? nothing : ints +end + +# interact3d definitions for beamlet propagation using trait dispatch +function interact3d_behavior(::Splitting, system::AbstractSystem, obj::AbstractObject, + coating_model, gauss::GaussianBeamlet, ray_id::Int) + return interact_splitting_boundary(system, obj, coating_model, gauss, ray_id) +end + +function interact3d_behavior( + ::CoatingBehavior, system::AbstractSystem, obj::AbstractObject, + coating_model, gauss::GaussianBeamlet, ray_id::Int) + ints = _interact3d_component_beams(system, obj, gauss, ray_id) + isnothing(ints) && return nothing + T = eltype(position(gauss.chief.rays[ray_id])) + return GaussianBeamletInteraction{T}(ints...) +end + +function interact3d_behavior(::Splitting, system::AbstractSystem, obj::AbstractObject, + coating_model, agb::AstigmaticGaussianBeamlet, ray_id::Int) + return interact_splitting_boundary(system, obj, coating_model, agb, ray_id) +end + +function interact3d_behavior( + ::CoatingBehavior, system::AbstractSystem, obj::AbstractObject, + coating_model, agb::AstigmaticGaussianBeamlet, ray_id::Int) + ints = _interact3d_component_beams(system, obj, agb, ray_id) + isnothing(ints) && return nothing + T = eltype(position(agb.c.rays[ray_id])) + return AstigmaticGaussianBeamletInteraction{T}(ints...) +end + +function interact3d_reflective(system::AbstractSystem, obj::AbstractObject, + coating_model, beam::AbstractBeam, ray::AbstractRay) + return interact_reflective_boundary(system, obj, coating_model, beam, ray) +end + +function interact3d_reflective(system::AbstractSystem, coating::Coating, + coating_model, beam::AbstractBeam, ray::AbstractRay) + normal, n_incident, n_transmitted, hint, λ, from_front = + _resolve_standalone_coating_context(system, coating, ray) + return interact_refractive_boundary( + Reflective(), system, coating, coating_model, beam, + ray, n_incident, n_transmitted, hint, normal, λ, from_front) +end + +@inline function _resolve_coated_splitting_context( + system::AbstractSystem, obj::AbstractObject, c_ray::AbstractRay) + int = intersection(c_ray) + λ = wavelength(c_ray) + n_substrate = is_refractive(obj) ? refractive_index(obj, λ) : refractive_index(system, λ) + + is_target_obj = (_base_optic(object(int)) === obj) + normal_coated = normal3d(int) + if !is_target_obj + normal_coated = -normal_coated + end + + entering_coated = dot(direction(c_ray), normal_coated) < 0 + + if entering_coated + n_incident = refractive_index(c_ray) + n_transmitted = n_substrate + normal = normal_coated + else + n_incident = n_substrate + other_obj = is_target_obj ? int.coincident_object : object(int) + if !isnothing(other_obj) && is_refractive(other_obj) + n_transmitted = refractive_index(other_obj, λ) + else + n_transmitted = refractive_index(system, λ) + end + normal = -normal_coated + end + + from_front = entering_coated + return (n_incident, n_transmitted, normal, from_front) +end + +function interact_splitting_boundary( + system::AbstractSystem, + obj::AbstractObject, + coating_model, + gauss::GaussianBeamlet, + ray_id::Int +) + c_ray = rays(gauss.chief)[ray_id] + n_incident, n_transmitted, normal, from_front = + _resolve_coated_splitting_context(system, obj, c_ray) + + return _propagate_splitting_gaussian_beamlet( + system, + obj, + coating_model, + gauss, + ray_id, + n_incident, + n_transmitted, + normal, + from_front, + () -> begin + ints = _interact3d_reflective_component_beams(system, obj, coating_model, gauss, ray_id) + isnothing(ints) && return nothing + T_type = eltype(position(c_ray)) + return GaussianBeamletInteraction{T_type}(ints...) + end + ) +end + +function interact_splitting_boundary( + system::AbstractSystem, + obj::AbstractObject, + coating_model, + agb::AstigmaticGaussianBeamlet, + ray_id::Int +) + # Ensure all component rays have valid intersections to prevent clipping crashes + beams = _component_beams(agb) + if any(b -> isnothing(intersection(rays(b)[ray_id])), beams) + return nothing + end + + c_ray = rays(agb.c)[ray_id] + n_incident, n_transmitted, normal, from_front = + _resolve_coated_splitting_context(system, obj, c_ray) + + return _propagate_splitting_astigmatic_beamlet( + system, + obj, + coating_model, + agb, + ray_id, + n_incident, + n_transmitted, + normal, + from_front, + () -> begin + ints = _interact3d_reflective_component_beams(system, obj, coating_model, agb, ray_id) + isnothing(ints) && return nothing + T_type = eltype(position(c_ray)) + return AstigmaticGaussianBeamletInteraction{T_type}(ints...) + end + ) +end diff --git a/src/OpticalComponents/Coatings/Models.jl b/src/OpticalComponents/Coatings/Models.jl new file mode 100644 index 000000000..41ab94cdc --- /dev/null +++ b/src/OpticalComponents/Coatings/Models.jl @@ -0,0 +1,520 @@ +# Coatings models, traits, and structs + +""" + AbstractCoating{T} <: AbstractObject{T} + +Base abstract type for standalone coating *objects* — thin coated boundaries that exist as +independent optical components in a system. This is distinct from coating *models* (such as +`SimpleARCoating`, `ThinFilmCoating`, etc.) which define the physical interaction properties +but are not optical objects themselves. +""" +abstract type AbstractCoating{T} <: AbstractObject{T} end + +is_thin_interface(::AbstractCoating) = true + +# Coating behavior traits +""" + CoatingBehavior + +Abstract trait representing the physical interaction behavior of a coating boundary. +The core physics engine dispatches ray and beamlet propagation logic based on this trait. +Subtypes are `Transmissive`, `Reflective`, `Splitting`, and `Absorptive`. +""" +abstract type CoatingBehavior end + +""" + Transmissive <: CoatingBehavior + +Trait indicating a coating boundary primarily intended to be traversed by light. +""" +struct Transmissive <: CoatingBehavior end + +""" + Reflective <: CoatingBehavior + +Trait indicating a coating boundary intended to reflect light back into the incident medium. +""" +struct Reflective <: CoatingBehavior end + +""" + Splitting <: CoatingBehavior + +Trait indicating a beam-splitting coating boundary that explicitly splits each incoming ray into both a transmitted and a reflected child ray. +""" +struct Splitting <: CoatingBehavior end + +""" + Absorptive <: CoatingBehavior + +Trait indicating a coating boundary that absorbs incident light. Rays hitting an absorptive +coating are terminated (the interaction returns `nothing`). +""" +struct Absorptive <: CoatingBehavior end + +# Coating models +""" + coating_behavior(coating, ray) + coating_behavior(coating) + +Query the physical interaction behavior trait of a coating (`Transmissive`, `Reflective`, or `Splitting`). +The two-argument version allows custom coating models to dynamically determine their behavior based on the incident ray parameters (e.g. angle of incidence, wavelength). +Falls back to `coating_behavior(coating)` for static behaviors. +""" +coating_behavior(c, ray) = coating_behavior(c) + +# Surface and Coating models, traits, and structs + +""" + AbstractSurfaceModel + +Base abstract type for all optical surface physics models (coatings, diffusers, diffractive surfaces, absorbing apertures, etc.). +""" +abstract type AbstractSurfaceModel end + +""" + AbstractCoatingModel <: AbstractSurfaceModel + +Base abstract type for thin-film, Jones, and dielectric coating models. +""" +abstract type AbstractCoatingModel <: AbstractSurfaceModel end + +""" + Uncoated + +Represents an uncoated dielectric boundary. Behaves as `Transmissive` by default. +""" +struct Uncoated <: AbstractCoatingModel end +coating_behavior(::Uncoated) = Transmissive() + +""" + is_coated(coating_model) + +Predicate indicating whether a coating model represents an active coating layer rather than an uncoated boundary (`Uncoated`). +""" +is_coated(::Uncoated) = false +is_coated(::AbstractCoatingModel) = true +is_coated(::Any) = true + +@inline get_coating_behavior(c) = coating_behavior(c) + +""" + SimpleARCoating(R::Real = 0.0) + +A simplified Anti-Reflective (AR) coating model defined by a constant power reflectance `R`. +Behaves as `Transmissive`. + +!!! warning "Angle Independence" + This model returns constant coefficients regardless of angle of incidence, wavelength, + or refractive index ratio. For angle-dependent AR behavior, use [`ThinFilmCoating`](@ref). +""" +struct SimpleARCoating{T <: Real} <: AbstractCoatingModel + R::T +end +SimpleARCoating() = SimpleARCoating(0.0) +coating_behavior(::SimpleARCoating) = Transmissive() + +""" + SimpleHRCoating(R::Real = 1.0) + +A simplified Highly Reflective (HR) coating model defined by a constant power reflectance `R`. +Behaves as `Reflective`. + +!!! warning "Angle Independence" + This model returns constant coefficients regardless of angle of incidence, wavelength, + or refractive index ratio. For angle-dependent HR behavior, use [`ThinFilmCoating`](@ref). +""" +struct SimpleHRCoating{T <: Real} <: AbstractCoatingModel + R::T +end +SimpleHRCoating() = SimpleHRCoating(1.0) +coating_behavior(::SimpleHRCoating) = Reflective() + +""" + SimpleBeamsplitterCoating(rs, rp, ts, tp) + +A simple beam-splitting coating defined by fixed complex amplitude reflection (`rs`, `rp`) and transmission (`ts`, `tp`) coefficients. +Behaves as `Splitting`. + +!!! note "Note on Transmission Coefficients" + The provided `ts` and `tp` values act effectively as the square roots of the power transmissivity, + rather than pure electric field amplitude transmission coefficients. The implementation implicitly + scales the resulting Jones matrix by the boundary impedance factor to ensure that ray intensity + strictly maps to optical power. +""" +struct SimpleBeamsplitterCoating{C <: Complex} <: AbstractCoatingModel + rs::C + rp::C + ts::C + tp::C +end +function SimpleBeamsplitterCoating(rs::Number, rp::Number, ts::Number, tp::Number) + T = promote_type(typeof(complex(rs)), typeof(complex(rp)), typeof(complex(ts)), typeof(complex(tp))) + return SimpleBeamsplitterCoating{T}(T(rs), T(rp), T(ts), T(tp)) +end +coating_behavior(::SimpleBeamsplitterCoating) = Splitting() + +""" + JonesCoating(jones_trans, jones_refl = XZBasis(0,0,0,0); behavior = Transmissive()) + +A fully generalized coating defined by its transmitted and reflected Jones matrices. +The Jones matrices can be constants (e.g. `SPBasis`, `XZBasis`) or functions taking wavelength `λ` and returning a `JonesMatrix`. + +!!! note "Transmission Scaling & Power Conservation" + When transmitting across an interface with different refractive indices (`n1 != n2`), + the transmitted Jones matrix is automatically scaled by the optical impedance factor + `sqrt((n1 * cos(θi)) / (n2 * cos(θt)))`. This ensures that the ray's electric field magnitude + `|E|²` directly maps to conserved optical power (Poynting flux). +""" +struct JonesCoating{JT, JR} <: AbstractCoatingModel + jones_trans::JT + jones_refl::JR + behavior::CoatingBehavior +end +JonesCoating(trans) = JonesCoating(trans, XZBasis(0, 0, 0, 0), Transmissive()) +JonesCoating(trans, refl; behavior = Transmissive()) = JonesCoating(trans, refl, behavior) +coating_behavior(c::JonesCoating) = c.behavior + +""" + ThinFilmCoating(ns::Vector, ds::Vector{<:Real}; behavior = Transmissive()) + ThinFilmCoating(n, d::Real; behavior = Transmissive()) + +A physical thin-film interference coating model defined by a stack of refractive indices `ns` and physical thicknesses `ds` (in same unit as wavelength, typically m). +Indices can be static real numbers or dispersion functions `f(λ) -> n`. +Calculates exact complex Fresnel coefficients using the characteristic transfer matrix method. + +!!! tip "Empty Layer Stack" + Passing empty vectors `ThinFilmCoating(Float64[], Float64[])` creates a bare interface + that yields the standard Fresnel coefficients for the surrounding media. This is useful + for modeling splitting at an uncoated index boundary. +""" +struct ThinFilmCoating{N <: Tuple, D <: Tuple, B <: CoatingBehavior} <: AbstractCoatingModel + ns::N + ds::D + behavior::B +end +function ThinFilmCoating( + n::Union{Number, Function}, d::Real; behavior::CoatingBehavior = Transmissive()) + return ThinFilmCoating((n,), (d,), behavior) +end +function ThinFilmCoating(ns::Union{AbstractVector, Tuple}, ds::Union{AbstractVector, Tuple}; + behavior::CoatingBehavior = Transmissive()) + ns_t = Tuple(ns) + ds_t = Tuple(ds) + return ThinFilmCoating(ns_t, ds_t, behavior) +end +coating_behavior(c::ThinFilmCoating) = c.behavior + +# fresnel_coefficients interface +fresnel_coefficients(::Uncoated, θi, λ, n1, n2) = fresnel_coefficients(θi, n2 / n1) + +function get_jones_matrix(::Uncoated, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + rs, rp, ts, tp = fresnel_coefficients(θi, n2 / n1) + if is_reflected + return SPBasis(-rs, 0, 0, rp) + else + return SPBasis(ts, 0, 0, tp) + end +end + +""" + unpolarized_reflectance(J) + +Compute the average power reflectance from a Jones reflection matrix for unpolarized light. + +!!! note "Absorption" + For non-absorbing coatings, `T = 1 - R` holds exactly. For absorbing coatings (complex + refractive index layers in a `ThinFilmCoating`), the absorbed fraction is accounted for such + that `T + R < 1`. Both `Ray` and `PolarizedRay` derive `T` via `coating_transmittance` + and `R` via `coating_reflectance` so that absorbed power `A = 1 - R - T` is properly deducted. +""" +@inline unpolarized_reflectance(J) = 0.5 * (abs2(J[1, 1]) + abs2(J[1, 2]) + abs2(J[2, 1]) + abs2(J[2, 2])) + +""" + unpolarized_transmittance(J) + +Compute the average power transmittance from a Jones transmission matrix for unpolarized light. +""" +@inline unpolarized_transmittance(J) = 0.5 * (abs2(J[1, 1]) + abs2(J[1, 2]) + abs2(J[2, 1]) + abs2(J[2, 2])) + +""" + coating_reflectance(coating, θi, λ, n1, n2; from_front=true, local_p=nothing) + +Compute the unpolarized power reflectance R ∈ [0, 1] of a coating model at angle of incidence `θi`. +""" +function coating_reflectance(c, θi, λ, n1, n2; from_front::Bool = true, local_p = nothing) + J_r = get_jones_matrix(c, θi, λ, n1, n2, true; from_front = from_front, local_p = local_p) + return clamp(unpolarized_reflectance(J_r), 0.0, 1.0) +end + +""" + coating_transmittance(coating, θi, λ, n1, n2; from_front=true, local_p=nothing) + +Compute the unpolarized power transmittance T ∈ [0, 1] of a coating model at angle of incidence `θi`. +""" +function coating_transmittance(c, θi, λ, n1, n2; from_front::Bool = true, local_p = nothing) + J_t = get_jones_matrix(c, θi, λ, n1, n2, false; from_front = from_front, local_p = local_p) + return clamp(unpolarized_transmittance(J_t), 0.0, 1.0) +end + +# Shared implementation for simplified constant-reflectance coating models +const SimpleReflectanceCoating = Union{SimpleARCoating, SimpleHRCoating} + +function fresnel_coefficients(c::SimpleReflectanceCoating, θi, λ, n1, n2) + R = c.R + T = 1.0 - R + rs = -sqrt(R) + rp = sqrt(R) + ts = sqrt(T) + tp = sqrt(T) + return rs, rp, ts, tp +end + +function get_jones_matrix( + c::SimpleReflectanceCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + rs, rp, ts, tp = fresnel_coefficients(c, θi, λ, n1, n2) + if is_reflected + return SPBasis(-rs, 0, 0, rp) + else + return SPBasis(ts, 0, 0, tp) + end +end + +fresnel_coefficients(c::SimpleBeamsplitterCoating, θi, λ, n1, n2) = (c.rs, c.rp, c.ts, c.tp) + +function get_jones_matrix(c::SimpleBeamsplitterCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + if is_reflected + rs = from_front ? c.rs : -c.rs + rp = from_front ? c.rp : -c.rp + return SPBasis(-rs, 0, 0, rp) + else + # Scale transmission coefficients to conserve power across index-mismatched boundaries + sinθt² = (n1 / n2)^2 * sin(θi)^2 + if sinθt² >= 1.0 + return SPBasis(0.0, 0.0, 0.0, 0.0) + else + cosθt = sqrt(1.0 - sinθt²) + scale = sqrt((n1 * cos(θi)) / (n2 * cosθt)) + return SPBasis(c.ts * scale, 0, 0, c.tp * scale) + end + end +end + +@inline _eval_jones(j::GlobalJonesBasis, ::Real) = j +@inline _eval_jones(j::LocalJonesBasis, ::Real) = j +@inline _eval_jones(j::Function, λ::Real) = j(λ) + +function get_jones_matrix( + c::JonesCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + if is_reflected + return _eval_jones(c.jones_refl, λ) + else + J = _eval_jones(c.jones_trans, λ) + if n1 ≈ n2 + return J + else + sinθt² = (n1 / n2)^2 * sin(θi)^2 + if sinθt² >= 1.0 + return typeof(J)(zero(static_data(J))) + else + cosθt = sqrt(1.0 - sinθt²) + scale = sqrt((n1 * cos(θi)) / (n2 * cosθt)) + return scale * J + end + end + end +end + +""" + coating_properties(coating, λ) + coating_properties(coating, λ, local_p) + +Query coating optical properties at wavelength `λ` and local spatial position `local_p`. +Falls back to `coating_properties(coating, λ)` for spatially uniform coatings. +""" +coating_properties(c::AbstractCoatingModel, λ::Real) = () + +@inline _eval_refractive_index(n::Function, λ::Real) = complex(n(λ)) +@inline _eval_refractive_index(n, λ::Real) = complex(n) + +function coating_properties(c::ThinFilmCoating, λ::Real) + n_vals = map(n -> _eval_refractive_index(n, λ), c.ns) + return n_vals, c.ds +end + +coating_properties(c::AbstractCoatingModel, λ::Real, local_p::AbstractVector) = coating_properties(c, λ) +coating_properties(c::AbstractCoatingModel, λ::Real, ::Nothing) = coating_properties(c, λ) + +function _fresnel_coefficients_matrix(n_vals, d_vals, θi::Real, λ::Real, + n1::Number, n2::Number; from_front::Bool = true) + sinθi = sin(θi) + cosθi = cos(θi) + + cosθt = sqrt(Complex(1.0 - (n1 / n2)^2 * sinθi^2)) + + η1s = n1 * cosθi + η2s = n2 * cosθt + + η1p = n1 / cosθi + η2p = n2 / cosθt + + # Initialize characteristic transfer matrices to Identity + m11_s = complex(1.0, 0.0) + m12_s = complex(0.0, 0.0) + m21_s = complex(0.0, 0.0) + m22_s = complex(1.0, 0.0) + + m11_p = complex(1.0, 0.0) + m12_p = complex(0.0, 0.0) + m21_p = complex(0.0, 0.0) + m22_p = complex(1.0, 0.0) + + N_layers = length(n_vals) + layer_indices = from_front ? (1:N_layers) : (N_layers:-1:1) + + for j in layer_indices + nj_val = n_vals[j] + dj = d_vals[j] + + cosθj = sqrt(Complex(1.0 - (n1 / nj_val)^2 * sinθi^2)) + δj = (2π / λ) * nj_val * dj * cosθj + + ηjs = nj_val * cosθj + ηjp = nj_val / cosθj + + cos_δj = cos(δj) + sin_δj = sin(δj) + + # Mjs components + Mjs11 = cos_δj + Mjs12 = im * sin_δj / ηjs + Mjs21 = im * ηjs * sin_δj + Mjs22 = cos_δj + + # Ms = Ms * Mjs + new_m11_s = m11_s * Mjs11 + m12_s * Mjs21 + new_m12_s = m11_s * Mjs12 + m12_s * Mjs22 + new_m21_s = m21_s * Mjs11 + m22_s * Mjs21 + new_m22_s = m21_s * Mjs12 + m22_s * Mjs22 + + m11_s, m12_s, m21_s, m22_s = new_m11_s, new_m12_s, new_m21_s, new_m22_s + + # Mjp components + Mjp11 = cos_δj + Mjp12 = im * sin_δj / ηjp + Mjp21 = im * ηjp * sin_δj + Mjp22 = cos_δj + + # Mp = Mp * Mjp + new_m11_p = m11_p * Mjp11 + m12_p * Mjp21 + new_m12_p = m11_p * Mjp12 + m12_p * Mjp22 + new_m21_p = m21_p * Mjp11 + m22_p * Mjp21 + new_m22_p = m21_p * Mjp12 + m22_p * Mjp22 + + m11_p, m12_p, m21_p, m22_p = new_m11_p, new_m12_p, new_m21_p, new_m22_p + end + + Bs = m11_s + η2s * m12_s + Cs = m21_s + η2s * m22_s + rs = (η1s * Bs - Cs) / (η1s * Bs + Cs) + ts = 2.0 * η1s / (η1s * Bs + Cs) + + Bp = m11_p + η2p * m12_p + Cp = m21_p + η2p * m22_p + rp = (η1p * Bp - Cp) / (η1p * Bp + Cp) + tp = (2.0 * η1p / (η1p * Bp + Cp)) * (cosθi / cosθt) + + return rs, rp, ts, tp +end + +function fresnel_coefficients(c::ThinFilmCoating, θi::Real, λ::Real, + n1::Number, n2::Number; from_front::Bool = true) + ns, ds = coating_properties(c, λ) + return _fresnel_coefficients_matrix(ns, ds, θi, λ, n1, n2; from_front = from_front) +end + +function get_jones_matrix( + c::ThinFilmCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + rs, rp, ts, tp = fresnel_coefficients(c, θi, λ, n1, n2; from_front = from_front) + if is_reflected + return SPBasis(-rs, 0, 0, rp) + else + return SPBasis(ts, 0, 0, tp) + end +end + +""" + GradedThinFilmCoating(thickness_func, base_coating::ThinFilmCoating) + +A spatially graded thin-film coating where layer thicknesses are scaled spatially by +`thickness_func(local_p)` at hit point `local_p`. +""" +struct GradedThinFilmCoating{F, C <: ThinFilmCoating} <: AbstractCoatingModel + thickness_func::F + base_coating::C +end + +coating_behavior(g::GradedThinFilmCoating) = coating_behavior(g.base_coating) + +function coating_properties(g::GradedThinFilmCoating, λ::Real, local_p::AbstractVector) + factor = g.thickness_func(local_p) + ns, ds = coating_properties(g.base_coating, λ) + return ns, ds .* factor +end + +function get_jones_matrix( + g::GradedThinFilmCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + factor = isnothing(local_p) ? 1.0 : g.thickness_func(local_p) + ns, ds = coating_properties(g.base_coating, λ) + ds_graded = ds .* factor + rs, rp, ts, tp = _fresnel_coefficients_matrix(ns, ds_graded, θi, λ, n1, n2; from_front = from_front) + if is_reflected + return SPBasis(-rs, 0, 0, rp) + else + return SPBasis(ts, 0, 0, tp) + end +end + +""" + CompositeSurfaceModel(models::AbstractSurfaceModel...) + +Composes multiple optical surface physics models sequentially. +Reflectance and transmittance matrices are multiplied across sub-models. +""" +struct CompositeSurfaceModel{T <: Tuple{Vararg{AbstractSurfaceModel}}} <: AbstractSurfaceModel + models::T +end + +CompositeSurfaceModel(models::AbstractSurfaceModel...) = CompositeSurfaceModel(models) + +@inline _behavior_precedence(::Absorptive) = 4 +@inline _behavior_precedence(::Splitting) = 3 +@inline _behavior_precedence(::Reflective) = 2 +@inline _behavior_precedence(::Transmissive) = 1 + +@inline _dominant_behavior(b1::CoatingBehavior, b2::CoatingBehavior) = + _behavior_precedence(b1) >= _behavior_precedence(b2) ? b1 : b2 + +function coating_behavior(comp::CompositeSurfaceModel) + return isempty(comp.models) ? Transmissive() : reduce(_dominant_behavior, map(coating_behavior, comp.models)) +end + +function get_jones_matrix( + comp::CompositeSurfaceModel, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) + J_tot = get_jones_matrix(comp.models[1], θi, λ, n1, n2, is_reflected; from_front = from_front, local_p = local_p) + for i in 2:length(comp.models) + J_i = get_jones_matrix(comp.models[i], θi, λ, n1, n2, is_reflected; from_front = from_front, local_p = local_p) + J_tot = J_i * J_tot + end + return J_tot +end + +# Base.show methods for coating models +Base.show(io::IO, ::MIME"text/plain", ::Uncoated) = print(io, "Uncoated") +Base.show(io::IO, ::MIME"text/plain", c::SimpleARCoating) = print(io, "SimpleARCoating(R = ", c.R, ")") +Base.show(io::IO, ::MIME"text/plain", c::SimpleHRCoating) = print(io, "SimpleHRCoating(R = ", c.R, ")") +Base.show(io::IO, ::MIME"text/plain", c::SimpleBeamsplitterCoating) = print(io, "SimpleBeamsplitterCoating(rs = ", c.rs, ", rp = ", c.rp, ", ts = ", c.ts, ", tp = ", c.tp, ")") +Base.show(io::IO, ::MIME"text/plain", c::JonesCoating) = print(io, "JonesCoating(behavior = ", c.behavior, ")") +Base.show(io::IO, ::MIME"text/plain", c::ThinFilmCoating) = print(io, "ThinFilmCoating(", length(c.ns), " layers, behavior = ", c.behavior, ")") +Base.show(io::IO, ::MIME"text/plain", c::GradedThinFilmCoating) = print(io, "GradedThinFilmCoating(base = ", c.base_coating, ")") +Base.show(io::IO, ::MIME"text/plain", c::CompositeSurfaceModel) = print(io, "CompositeSurfaceModel(", length(c.models), " models)") + diff --git a/src/OpticalComponents/Coatings/StandaloneCoating.jl b/src/OpticalComponents/Coatings/StandaloneCoating.jl new file mode 100644 index 000000000..068f167a1 --- /dev/null +++ b/src/OpticalComponents/Coatings/StandaloneCoating.jl @@ -0,0 +1,261 @@ +# Standalone Coating struct and ray/beamlet interaction methods + +# Coating object wrapping a shape and a model +""" + Coating(shape, model; side = :either) + Coating{T, S, M} <: AbstractCoating{T} + +A standalone optical component representing an infinitesimally thin coated boundary floating in space. +Wraps an `AbstractShape` and a coating model `M` (e.g. `ThinFilmCoating`, `SimpleBeamsplitterCoating`). +Can be configured to only interact with light hitting a specific `side` (e.g. `:front` or `:back`), passing straight through from the other direction without effect. +""" +struct Coating{T <: Real, S <: AbstractShape{T}, M} <: AbstractCoating{T} + shape::S + model::M + normal_filter::Union{Nothing, SVector{3, Float64}} +end + +function Coating(shape::AbstractShape{T}, model, side::Symbol) where {T} + normal_filter = if side == :front + SVector{3, Float64}(0.0, -1.0, 0.0) + elseif side == :back + SVector{3, Float64}(0.0, 1.0, 0.0) + else + nothing + end + return Coating{T, typeof(shape), typeof(model)}(shape, model, normal_filter) +end + +function Coating(shape::AbstractShape{T}, model, + normal_filter::Union{Nothing, AbstractVector}) where {T} + nf = isnothing(normal_filter) ? nothing : SVector{3, Float64}(normal_filter) + return Coating{T, typeof(shape), typeof(model)}(shape, model, nf) +end + +function Coating(shape::AbstractShape{T}, model; side::Symbol = :either, + normal_filter = nothing) where {T} + nf = if !isnothing(normal_filter) + SVector{3, Float64}(normal_filter) + elseif side == :front + SVector{3, Float64}(0.0, -1.0, 0.0) + elseif side == :back + SVector{3, Float64}(0.0, 1.0, 0.0) + else + nothing + end + return Coating{T, typeof(shape), typeof(model)}(shape, model, nf) +end + +shape_trait_of(::Coating) = SingleShape() +shape(c::Coating) = c.shape + +function intersect3d(::SingleShape, coating::Coating, ray::AbstractRay) + int = intersect3d(shape(coating), ray) + isnothing(int) && return nothing + + if !isnothing(coating.normal_filter) + wn = normal3d(int) + parent_shape = shape(coating) + local_n = transposed_orientation(parent_shape) * wn + # A threshold of 0.5 corresponds to cos(60°), restricting the interaction + # to rays hitting the surface within a ±60° angle of the target normal direction. + if dot(local_n, coating.normal_filter) <= 0.5 + return nothing + end + end + + object!(int, coating) + return int +end + +@inline function _coating_media(system::AbstractSystem, ray::AbstractRay, int::Intersection) + λ = wavelength(ray) + n_incident = refractive_index(ray) + n_sys = refractive_index(system, λ) + + n_exit = (!isnothing(int.coincident_object) && is_refractive(int.coincident_object)) ? + refractive_index(int.coincident_object, λ) : n_sys + n_enter = (!isnothing(int.coincident_object_2) && + is_refractive(int.coincident_object_2)) ? + refractive_index(int.coincident_object_2, λ) : n_sys + + tol = get_index_matching_tolerance() + if abs(n_incident - n_exit) < tol + n_transmitted = n_enter + n_reflected = n_exit + else + n_transmitted = n_exit + n_reflected = n_enter + end + return n_transmitted, n_reflected +end + +""" + _resolve_coincident_hint(system, ray, int, is_entering) + +Resolves the target object hint (`Hint`) at a standalone coating boundary by comparing the ray's +current refractive index against the coincident adjacent objects (`coincident_object` and `coincident_object_2`). +If `is_entering` is `true`, returns the object entered upon transmission; otherwise returns the object remaining in upon reflection. +""" +@inline function _resolve_coincident_hint( + system::AbstractSystem, ray::AbstractRay, int::Intersection, is_entering::Bool) + n_exit = int.coincident_object + n_enter = int.coincident_object_2 + (isnothing(n_exit) && isnothing(n_enter)) && return nothing + + λ = wavelength(ray) + n_sys = refractive_index(system, λ) + n_exit_val = isnothing(n_exit) ? n_sys : + (is_refractive(n_exit) ? refractive_index(n_exit, λ) : n_sys) + + tol = get_index_matching_tolerance() + is_matching = abs(refractive_index(ray) - n_exit_val) < tol + target_obj = is_entering ? (is_matching ? n_enter : n_exit) : (is_matching ? n_exit : n_enter) + return isnothing(target_obj) ? nothing : Hint(target_obj) +end + +""" + _resolve_coating_normal(ray, int) + +Computes the interface normal vector aligned against the incoming ray direction (`-normal`), along with +the boolean `from_front` flag indicating whether the ray hit the interface from the front side. +""" +@inline function _resolve_coating_normal(ray::AbstractRay, int::Intersection) + normal = normal3d(int) + from_front = dot(direction(ray), normal) < 0 + return from_front ? normal : -normal, from_front +end + +@inline function _resolve_standalone_coating_context( + system::AbstractSystem, coating::Coating, ray::AbstractRay) + int = intersection(ray) + λ = wavelength(ray) + n_transmitted, _ = _coating_media(system, ray, int) + normal, from_front = _resolve_coating_normal(ray, int) + hint_trans = _resolve_coincident_hint(system, ray, int, true) + n_incident = refractive_index(ray) + return (normal, n_incident, n_transmitted, hint_trans, λ, from_front) +end + +# Route interact3d through coating_behavior trait into unified boundary physics engine +function interact3d(system::AbstractSystem, coating::Coating{T}, + beam::AbstractBeam, ray::AbstractRay) where {T} + normal, n_incident, n_transmitted, hint, λ, from_front = + _resolve_standalone_coating_context(system, coating, ray) + behavior = coating_behavior(coating.model, ray) + return interact_refractive_boundary( + behavior, system, coating, coating.model, beam, + ray, n_incident, n_transmitted, hint, normal, λ, from_front) +end + +# GaussianBeamlet and AstigmaticGaussianBeamlet splitting methods +function interact3d(system::AbstractSystem, coating::Coating{T}, + gauss::GaussianBeamlet, ray_id::Int) where {T} + chief_ray = rays(gauss.chief)[ray_id] + return interact3d( + coating_behavior(coating.model, chief_ray), system, coating, gauss, ray_id) +end + +function interact3d(::CoatingBehavior, system::AbstractSystem, coating::Coating{T}, + gauss::GaussianBeamlet, ray_id::Int) where {T} + # For transmissive or reflective coatings, they act as single-beam interactions (no splitting), + # so we fall back to the generic GaussianBeamlet interaction. + i_c = interact3d(system, coating, gauss.chief, rays(gauss.chief)[ray_id]) + i_w = interact3d(system, coating, gauss.waist, rays(gauss.waist)[ray_id]) + i_d = interact3d(system, coating, gauss.divergence, rays(gauss.divergence)[ray_id]) + if any(isnothing, (i_c, i_w, i_d)) + return nothing + end + return GaussianBeamletInteraction{T}(i_c, i_w, i_d) +end + +function interact3d(::Splitting, system::AbstractSystem, coating::Coating{T}, + gauss::GaussianBeamlet, ray_id::Int) where {T} + # Ensure all component rays have valid intersections to prevent clipping crashes + if isnothing(intersection(gauss.chief.rays[ray_id])) || + isnothing(intersection(gauss.waist.rays[ray_id])) || + isnothing(intersection(gauss.divergence.rays[ray_id])) + return nothing + end + + c_ray = gauss.chief.rays[ray_id] + int = intersection(c_ray) + n_transmitted, _ = _coating_media(system, c_ray, int) + normal, from_front = _resolve_coating_normal(c_ray, int) + + return _propagate_splitting_gaussian_beamlet( + system, + coating, + coating.model, + gauss, + ray_id, + refractive_index(c_ray), + n_transmitted, + normal, + from_front, + () -> begin + ints = _interact3d_reflective_component_beams(system, coating, coating.model, gauss, ray_id) + isnothing(ints) && return nothing + return GaussianBeamletInteraction{T}(ints...) + end + ) +end + +function interact3d(system::AbstractSystem, coating::Coating{T}, + agb::AstigmaticGaussianBeamlet, ray_id::Int) where {T} + chief_ray = rays(agb.c)[ray_id] + return interact3d( + coating_behavior(coating.model, chief_ray), system, coating, agb, ray_id) +end + +function interact3d(::CoatingBehavior, system::AbstractSystem, coating::Coating{T}, + agb::AstigmaticGaussianBeamlet, ray_id::Int) where {T} + ints = _interact3d_component_beams(system, coating, agb, ray_id) + isnothing(ints) && return nothing + return AstigmaticGaussianBeamletInteraction{T}(ints...) +end + +function interact3d(::Splitting, system::AbstractSystem, coating::Coating{T}, + agb::AstigmaticGaussianBeamlet, ray_id::Int) where {T} + # Ensure all component rays have valid intersections to prevent clipping crashes + beams = _component_beams(agb) + if any(b -> isnothing(intersection(rays(b)[ray_id])), beams) + return nothing + end + + c_ray = rays(agb.c)[ray_id] + int = intersection(c_ray) + n_transmitted, _ = _coating_media(system, c_ray, int) + normal, from_front = _resolve_coating_normal(c_ray, int) + + return _propagate_splitting_astigmatic_beamlet( + system, + coating, + coating.model, + agb, + ray_id, + refractive_index(c_ray), + n_transmitted, + normal, + from_front, + () -> begin + ints = _interact3d_reflective_component_beams(system, coating, coating.model, agb, ray_id) + isnothing(ints) && return nothing + return AstigmaticGaussianBeamletInteraction{T}(ints...) + end + ) +end + +# Absorptive behavior +function interact3d(::Absorptive, ::AbstractSystem, ::Coating{T}, + ::AbstractBeam, ::AbstractRay) where {T} + nothing +end +function interact3d( + ::Absorptive, ::AbstractSystem, ::Coating{T}, ::GaussianBeamlet, ::Int) where {T} + nothing +end +function interact3d(::Absorptive, ::AbstractSystem, ::Coating{T}, + ::AstigmaticGaussianBeamlet, ::Int) where {T} + nothing +end diff --git a/src/OpticalComponents/Components.jl b/src/OpticalComponents/Components.jl index d7a65a645..4566de3eb 100644 --- a/src/OpticalComponents/Components.jl +++ b/src/OpticalComponents/Components.jl @@ -1,10 +1,15 @@ # Order of inclusion matters! +include("FacePartition.jl") +include("Coatings/Models.jl") +include("Coatings/BoundaryPhysics.jl") +include("Coatings/StandaloneCoating.jl") include("Mirrors.jl") include("Lenses.jl") include("Prisms.jl") include("SphericalLenses.jl") include("DoubletLenses.jl") +include("Coatings/CoatedComponents.jl") include("Detectors/Detector.jl") include("Beamsplitters/Beamsplitters.jl") include("NonInteractable.jl") diff --git a/src/OpticalComponents/FacePartition.jl b/src/OpticalComponents/FacePartition.jl new file mode 100644 index 000000000..c28a9db3c --- /dev/null +++ b/src/OpticalComponents/FacePartition.jl @@ -0,0 +1,90 @@ +# Fallback for transposed orientation +transposed_orientation(shape::AbstractShape) = transpose(orientation(shape)) + +""" + world_to_local(shape::AbstractShape, point::AbstractVector) + +Transforms coordinate `point` from world space to the local coordinate system of `shape`. +""" +function world_to_local(shape::AbstractSDF, point::AbstractVector) + return _world_to_sdf(shape, point) +end + +function world_to_local(shape::AbstractShape, point::AbstractVector) + T = transposed_orientation(shape) + return T * (point - position(shape)) +end + +""" + face_id(shape::AbstractShape, local_n::AbstractVector)::Symbol + +Partition the surface normal space of a shape into named faces (e.g., `:front`, `:back`, `:side`, `:hypotenuse`). +Returns a `Symbol` corresponding to the face that contains the given `local_n` vector (in local shape coordinates). +""" +function face_id(shape::AbstractShape, local_n::AbstractVector) + # Default fallback for rotationally symmetric/general shapes: + # y-axis is the optical axis in BMO. + # Front is pointing in -y direction. + # Back is pointing in +y direction. + ny = local_n[2] + if ny < -0.1 + return :front + elseif ny > 0.1 + return :back + else + return :side + end +end + +# Specialization for BoxSDF +function face_id(shape::BoxSDF, local_n::AbstractVector) + ny = local_n[2] + nx = local_n[1] + nz = local_n[3] + d_front = -ny + d_back = ny + d_right = nx + d_left = -nx + d_top = nz + d_bottom = -nz + best_face = argmax((d_front, d_back, d_right, d_left, d_top, d_bottom)) + return (:front, :back, :right, :left, :top, :bottom)[best_face] +end + +# Specialization for CylinderSDF +function face_id(shape::CylinderSDF, local_n::AbstractVector) + ny = local_n[2] + if ny > 0.5 + return :top + elseif ny < -0.5 + return :bottom + else + return :side + end +end + +# Specialization for RightAnglePrismSDF +function face_id(shape::RightAnglePrismSDF, local_n::AbstractVector) + # Face normals: + # - Hypotenuse: [1.0, 1.0, 0.0] / √2 + # - Leg 1: [-1.0, 0.0, 0.0] + # - Leg 2: [0.0, -1.0, 0.0] + # - Zpos: [0.0, 0.0, 1.0] + # - Zneg: [0.0, 0.0, -1.0] + d_hyp = dot(local_n, SVector(1.0, 1.0, 0.0) / √2) + d_leg1 = dot(local_n, SVector(-1.0, 0.0, 0.0)) + d_leg2 = dot(local_n, SVector(0.0, -1.0, 0.0)) + d_zpos = dot(local_n, SVector(0.0, 0.0, 1.0)) + d_zneg = dot(local_n, SVector(0.0, 0.0, -1.0)) + + best_face = argmax((d_hyp, d_leg1, d_leg2, d_zpos, d_zneg)) + return (:hypotenuse, :leg1, :leg2, :zpos, :zneg)[best_face] +end + +""" + surface_tag(shape::AbstractShape, local_p, local_n) + +Returns a symbolic surface tag (e.g. `:front`, `:back`, `:side`, `:top`, `:bottom`, `:hypotenuse`, `:leg1`, `:leg2`) +for a hit point on the shape. Defaults to `face_id(shape, local_n)`. +""" +surface_tag(s::AbstractShape, local_p, local_n) = face_id(s, local_n) diff --git a/src/OpticalComponents/Polarizers/JonesCalculus.jl b/src/OpticalComponents/Polarizers/JonesCalculus.jl index 89b4f34f2..2ca5c1cf1 100644 --- a/src/OpticalComponents/Polarizers/JonesCalculus.jl +++ b/src/OpticalComponents/Polarizers/JonesCalculus.jl @@ -1,47 +1,18 @@ -""" - AbstractJonesPolarizer <: AbstractObject - -Represents infinitesimally thin components that change the polarization state of incoming [`PolarizedRay`](@ref)s via global Jones matrix calculus. -Rather than using the generic Yun ray tracing scheme as referred to in the `PolarizedRay` docs, this element interacts with -the global E-field vector `E0` by using a [`GlobalJonesBasis`](@ref) and projecting the entries into the transverse plane defined -by the incoming ray direction and orthogonal E-field vector. This approach is partially inspired by the publication: +# Jones Matrix calculation helpers -**Jan Korger et al., "The polarization properties of a tilted polarizer," Opt. Express 21, 27032-27042 (2013)** - -!!! warning - It is assumed that the ray direction of propagation is not changed during the interaction. - -# Implementation reqs. - -Subtypes of `AbstractJonesPolarizer` should implement all supertype requirements. - -## Interaction logic - -The [`GlobalJonesBasis`](@ref) tracks the rotation in 3D-space via the [`orientation`](@ref) of the attached [`AbstractShape`](@ref). -The polarization matrix `P` is calculated by projecting the previous matrix into the incoming orthogonal plane of polarization. -Refer to the [`_calculate_global_E0`](@ref) implementation for more information. - -!!! info - The validity of this approach is still under consideration for non-normal incidence. -""" -abstract type AbstractJonesPolarizer{T} <: AbstractObject{T} end - -function _calculate_global_E0(object::AbstractJonesPolarizer, ray::PolarizedRay, out_dir::AbstractArray, J::GlobalJonesBasis) +function _calculate_global_E0(object::AbstractObject, ray::PolarizedRay, + out_dir::AbstractArray, J::GlobalJonesBasis) in_dir = direction(ray) E0 = polarization(ray) - if !isparallel3d(in_dir, out_dir) - # Not sure how good this implementation works - throw(ErrorException("Thin film polarizer _calculate_global_E0 only works if no direction change occurs.")) - end # Transform Jones matrix according to global object orientation R = orientation(object) P = R * J * transpose(R) - # Calculate projection of P into ray-E0-transverse plane - # Note: this in general violates P*in_dir = out_dir - Q = I - in_dir * transpose(in_dir) - # technically Q*P*transpose(Q), but Q=Q^T - P = Q * P * Q - return P*E0 + + Q_in = I - in_dir * transpose(in_dir) + Q_out = I - out_dir * transpose(out_dir) + P = Q_out * P * Q_in + out_dir * transpose(in_dir) + return P * E0 end -include("PolarizationFilter.jl") \ No newline at end of file +include("PolarizationFilter.jl") +include("Waveplate.jl") \ No newline at end of file diff --git a/src/PolarizedRays.jl b/src/PolarizedRays.jl index 18dbd1efc..c1c3df14c 100644 --- a/src/PolarizedRays.jl +++ b/src/PolarizedRays.jl @@ -39,7 +39,7 @@ mutable struct PolarizedRay{T} <: AbstractRay{T} dir::Point3{T} intersection::Nullable{Intersection{T}} λ::T - n::T + n::Union{T, Complex{T}} E0::Point3{Complex{T}} function PolarizedRay{T}( pos::AbstractArray{P}, @@ -49,7 +49,7 @@ mutable struct PolarizedRay{T} <: AbstractRay{T} n::N, E0::AbstractArray{<:Union{E, Complex{E}}} ) where {T, P, D, L, N, E} - M = promote_type(T, P, D, L, N, E) + M = promote_type(T, P, D, L, real(N), real(E)) if isapprox(norm(dir), 0, atol=1e-14) throw(ErrorException("Direction vector to short for normalization.")) end @@ -62,7 +62,7 @@ mutable struct PolarizedRay{T} <: AbstractRay{T} normalize(Point3{M}(dir)), int, M(λ), - M(n), + (n isa Complex ? Complex{M}(n) : M(n)), Point3{Complex{M}}(E0) ) end @@ -152,6 +152,12 @@ XYBasis(j11::Number, j12::Number, j21::Number, j22::Number) = GlobalJonesBasis(@ XZBasis(j11::Number, j12::Number, j21::Number, j22::Number) = GlobalJonesBasis(@SArray([j11 0 j12; 0 1 0; j21 0 j22])) YZBasis(j11::Number, j12::Number, j21::Number, j22::Number) = GlobalJonesBasis(@SArray([1 0 0; 0 j22 j21; 0 j12 j11])) +Base.:*(val::Number, J::GlobalJonesBasis) = GlobalJonesBasis(val * static_data(J)) +Base.:*(J::GlobalJonesBasis, val::Number) = GlobalJonesBasis(static_data(J) * val) + +Base.:*(val::Number, J::LocalJonesBasis) = LocalJonesBasis(val * static_data(J)) +Base.:*(J::LocalJonesBasis, val::Number) = LocalJonesBasis(static_data(J) * val) + """ _calculate_global_E0(in_dir, out_dir, normal, J) @@ -166,29 +172,40 @@ is chosen for the s- and p-components. - `J`: Jones matrix extended to 3x3, e.g. [-rₛ 0 0; 0 rₚ 0; 0 0 1] for reflection """ function _calculate_global_E0(in_dir::AbstractArray, out_dir::AbstractArray, normal::AbstractArray, J::LocalJonesBasis) - # Choose basis vectors - if !isparallel3d(in_dir, out_dir) - v = out_dir + k_in = normalize(in_dir) + k_out = normalize(out_dir) + n = normalize(normal) + + # Test if in-dir and normal are parallel (normal incidence) + if isparallel3d(k_in, n) + s = normal3d(k_in) else - v = normal + s = cross(k_in, n) + s = normalize(s) end - # test if in-dir and normal are parallel - if isparallel3d(in_dir, normal) - # Does this really always work for normal s-p-incidence? - v = normal3d(in_dir) - end - # Calculate support vector - s = cross(in_dir, v) - s = normalize(s) + # Calculate transforms - p1 = cross(in_dir, s) - O_in = vcat(s', p1', in_dir') + p1 = cross(k_in, s) + O_in = @SArray [ + s[1] s[2] s[3]; + p1[1] p1[2] p1[3]; + k_in[1] k_in[2] k_in[3] + ] + # Fallback method as per eq. 17 - if isparallel3d(in_dir, out_dir) && !(in_dir ≈ -out_dir) - O_out = hcat(s, p1, in_dir) + if isparallel3d(k_in, k_out) && !(k_in ≈ -k_out) + O_out = @SArray [ + s[1] p1[1] k_in[1]; + s[2] p1[2] k_in[2]; + s[3] p1[3] k_in[3] + ] else - p2 = cross(out_dir, s) - O_out = hcat(s, p2, out_dir) + p2 = cross(k_out, s) + O_out = @SArray [ + s[1] p2[1] k_out[1]; + s[2] p2[2] k_out[2]; + s[3] p2[3] k_out[3] + ] end # Calculate new E0 P = O_out * J * O_in diff --git a/src/Rays.jl b/src/Rays.jl index 1efd2b7ca..6e3612bf7 100644 --- a/src/Rays.jl +++ b/src/Rays.jl @@ -16,9 +16,23 @@ mutable struct Ray{T} <: AbstractRay{T} dir::Point3{T} intersection::Nullable{Intersection{T}} λ::T - n::T + n::Union{T, Complex{T}} + weight::T + + function Ray{T}(pos::AbstractArray, dir::AbstractArray, int::Nullable{Intersection}, λ::Real, n::Number, weight::Real = one(T)) where {T} + return new{T}( + Point3{T}(pos), + normalize(Point3{T}(dir)), + int, + T(λ), + (n isa Complex ? Complex{T}(n) : T(n)), + T(weight) + ) + end end +Ray{T}(pos, dir, int, λ, n) where {T} = Ray{T}(pos, dir, int, λ, n, one(T)) + """ Ray(pos, dir, λ=1000e-9) @@ -41,5 +55,20 @@ function Ray(pos::AbstractArray{P}, normalize(Point3{F}(dir)), nothing, F(λ), - F(1)) -end \ No newline at end of file + F(1), + F(1) + ) +end + +function Ray(pos::AbstractArray{P}, + dir::AbstractArray{D}, + int::Nullable{Intersection}, + λ::L, + n::N = 1, + weight::W = 1) where {P <: Real, D <: Real, L <: Real, N <: Number, W <: Real} + F = promote_type(P, D, L, real(N), W) + return Ray{F}(pos, dir, int, λ, n, weight) +end + +weight(ray::Ray) = ray.weight +weight!(ray::Ray, w::Real) = (ray.weight = w) \ No newline at end of file diff --git a/src/System.jl b/src/System.jl index 1d5ade609..d195add61 100644 --- a/src/System.jl +++ b/src/System.jl @@ -56,36 +56,123 @@ function retrace_system!(::AbstractSystem, beam::B) where {B <: AbstractBeam} return nothing end +@inline resolve_coincident_boundary(exiting_int, entering_int) = resolve_coincident_boundary( + exiting_int, entering_int, object(exiting_int), object(entering_int)) + +@inline function resolve_coincident_boundary( + exiting_int, entering_int, ::AbstractObject, ::AbstractObject) + exiting_int.coincident_object = object(entering_int) + return exiting_int +end + +""" + _resolve_coincident_group(thin_primary, exiting_int, entering_int, fallback_int) + +Resolves the primary intersection and assigns adjacent coincident objects for thin-interface coatings +and flush bulk optical boundaries (e.g., cemented doublet lenses). +""" +@inline function _resolve_coincident_group( + thin_primary, exiting_int, entering_int, fallback_int) + if thin_primary !== nothing + thin_primary.coincident_object = exiting_int !== nothing ? object(exiting_int) : + nothing + thin_primary.coincident_object_2 = entering_int !== nothing ? object(entering_int) : + nothing + return thin_primary + elseif exiting_int !== nothing && entering_int !== nothing + return resolve_coincident_boundary(exiting_int, entering_int) + elseif exiting_int !== nothing + return exiting_int + elseif entering_int !== nothing + return entering_int + else + return fallback_int + end +end + @inline function trace_all(system::AbstractSystem, ray::AbstractRay{R}) where {R} - result::Union{Nothing, Intersection{R}} = nothing + tol = get_coincident_boundary_tolerance() + best_t = R(Inf) + best_int = nothing + thin_primary = nothing + exiting_int = nothing + entering_int = nothing + + # Find the closest intersection and collect any coincident ones at the same distance for obj in objects(system) - # Find shortest intersection - temp::Union{Nothing, Intersection{R}} = intersect3d(obj, ray) - if temp === nothing + temp = intersect3d(obj, ray) + (temp === nothing || length(temp) <= tol) && continue + t = length(temp) + + if t < best_t - tol + best_t = t + best_int = temp + thin_primary = exiting_int = entering_int = nothing + elseif abs(t - best_t) > tol continue end - # Catch first valid intersection and replace current with closer intersection - if result === nothing || length(temp) < length(result) - result = temp + if is_thin_interface(object(temp)) + thin_primary = temp + elseif dot(direction(ray), normal3d(temp)) > 0 + exiting_int = temp + else + entering_int = temp end end - return result + + best_int === nothing && return nothing + return _resolve_coincident_group(thin_primary, exiting_int, entering_int, best_int) end @inline function trace_one( system::AbstractSystem, ray::AbstractRay{R}, hint::Hint) where {R} - # Trace against hinted shape of object - intersection::Nullable{Intersection{R}} = intersect3d( + tol = get_coincident_boundary_tolerance() + # Trace against hinted shape of object first + primary = intersect3d( shape(hint)::AbstractShape{R}, ray) - if isnothing(intersection) + if primary === nothing # If hinted object is not intersected, trace the entire system - intersection = trace_all(system, ray) + return trace_all(system, ray) + end + + object!(primary, object(hint)) + t_best = length(primary) + if t_best <= tol + # Ignore self-intersection/coincident boundary re-entry + return trace_all(system, ray) + end + + thin_primary = nothing + exiting_int = nothing + entering_int = nothing + + if is_thin_interface(object(primary)) + thin_primary = primary + elseif dot(direction(ray), normal3d(primary)) > 0 + exiting_int = primary else - # If hinted object is intersected, update intersection - object!(intersection, object(hint)) + entering_int = primary + end + + # Gather other intersections at the same distance to resolve cement/contact transitions + for obj in objects(system) + if obj === object(hint) + continue + end + temp = intersect3d(obj, ray) + if temp !== nothing && abs(length(temp) - t_best) <= tol + if is_thin_interface(object(temp)) + thin_primary = temp + elseif dot(direction(ray), normal3d(temp)) > 0 + exiting_int = temp + else + entering_int = temp + end + end end - return intersection + + return _resolve_coincident_group(thin_primary, exiting_int, entering_int, primary) end """ @@ -228,25 +315,21 @@ function retrace_system!( end # Recalculate current intersection if isnothing(_hint) - # Retrace intersection - intersection!(ray, intersect3d(object(_intersection), ray)) + intersection!(ray, trace_all(system, ray)) else - # Retrace hint - intersection!(ray, intersect3d(shape(_hint), ray)) - if !isnothing(intersection(ray)) - object!(intersection(ray), object(_hint)) - end + intersection!(ray, trace_one(system, ray, _hint)) end - # Test if intersection is valid - if isnothing(intersection(ray)) + # Test if intersection and object are valid + int = intersection(ray) + _obj = isnothing(int) ? nothing : object(int) + if isnothing(_obj) cleanup_children = true cleanup_tail = true reset_intersection = true cutoff = i break end - # Test if interaction is still valid - _interaction = interact3d(system, object(intersection(ray)), beam, ray) + _interaction = interact3d(system, _obj, beam, ray) # Catch hint _hint = hint(_interaction) if isnothing(_interaction) @@ -258,7 +341,7 @@ function retrace_system!( break end if i < length(rays(beam)) - # Modify following ray (NOT THREAD-SAFE) + # Mutate following ray in-place (confined to current beam instance) replace!(beam, _interaction, i + 1) else # Valid new interaction, drop children and add new ray @@ -304,28 +387,26 @@ function trace_system!( interaction::Nullable{GaussianBeamletInteraction{T}} = nothing # Buffer variable seg_counter::Int = length(rays(gauss.chief)) + beams = _component_beams(gauss) while seg_counter < r_max - # Trace chief ray first - ray = last(rays(gauss.chief)) - tracing_step!(system, ray, hint(interaction)) - isnothing(intersection(ray)) && break - _object = object(intersection(ray)) - # Follow up with waist ray - ray = last(rays(gauss.waist)) - tracing_step!(system, ray, hint(interaction)) - # if the waist ray is no longer hitting the same object as the chief ray stop here - isnothing(intersection(ray)) && break - # Follow up with divergence ray - ray = last(rays(gauss.divergence)) - tracing_step!(system, ray, hint(interaction)) - # if the divergence ray is no longer hitting the same object as the chief ray stop here - isnothing(intersection(ray)) && break - # If beams do not hit same target stop tracing - if !_beams_hits_same_shape(gauss, seg_counter) - # Ensure that no intersection artifacts remain - intersection!(last(rays(gauss.chief)), nothing) - intersection!(last(rays(gauss.waist)), nothing) - intersection!(last(rays(gauss.divergence)), nothing) + h = hint(interaction) + stopped = false + for b in beams + r = last(rays(b)) + tracing_step!(system, r, h) + if isnothing(intersection(r)) + stopped = true + break + end + end + if stopped || !_beams_hits_same_shape(gauss, seg_counter) + for b in beams + intersection!(last(rays(b)), nothing) + end + break + end + _object = object(intersection(last(rays(gauss.chief)))) + if isnothing(_object) break end # Calculate interaction @@ -363,39 +444,25 @@ function retrace_system!( # Buffer variables _interaction::Nullable{GaussianBeamletInteraction{T}} = nothing _hint::Nullable{Hint} = nothing + beams = _component_beams(gauss) # Test if gauss beam is healthy n_c = length(rays(gauss.chief)) - n_w = length(rays(gauss.waist)) - n_d = length(rays(gauss.divergence)) - if !(n_c == n_w == n_d) + if !all(b -> length(rays(b)) == n_c, beams) error("Gaussian beamlet is broken") end # Iterate over chief rays for (i, c_ray) in enumerate(rays(gauss.chief)) - # Test if intersection is valid - _intersection = intersection(c_ray) - if isnothing(_intersection) - cleanup_children = true - cleanup_tail = true - reset_intersection = true - cutoff = i - break - end - # Recalculate current intersection (use shape of hint if available) - w_ray = rays(gauss.waist)[i] - d_ray = rays(gauss.divergence)[i] + # Recalculate current intersection if isnothing(_hint) - _object = object(_intersection) - _shape = shape(_intersection) - intersection!(c_ray, intersect3d(_object, c_ray)) - intersection!(w_ray, intersect3d(_object, w_ray)) - intersection!(d_ray, intersect3d(_object, d_ray)) + for b in beams + r = rays(b)[i] + intersection!(r, trace_all(system, r)) + end else - _object = object(_hint) - _shape = BeamletOptics.shape(_hint) - intersection!(c_ray, intersect3d(_shape, c_ray)) - intersection!(w_ray, intersect3d(_shape, w_ray)) - intersection!(d_ray, intersect3d(_shape, d_ray)) + for b in beams + r = rays(b)[i] + intersection!(r, trace_one(system, r, _hint)) + end end # Test if all beams still hit the same target if !_beams_hits_same_shape(gauss, i) @@ -405,18 +472,20 @@ function retrace_system!( cutoff = i break end - # Test if valid intersection - if isnothing(intersection(c_ray)) + # Test if valid intersection and object + c_int = intersection(c_ray) + _object = isnothing(c_int) ? nothing : object(c_int) + if isnothing(_object) cleanup_children = true cleanup_tail = true reset_intersection = true cutoff = i break end - # Update object field - object!(intersection(c_ray), _object) - object!(intersection(w_ray), _object) - object!(intersection(d_ray), _object) + for b in beams + r_int = intersection(rays(b)[i]) + !isnothing(r_int) && object!(r_int, _object) + end # Test if interaction is still valid _interaction = interact3d(system, _object, gauss, i) # Catch hint @@ -431,7 +500,7 @@ function retrace_system!( end # Update next beamlet section if i < n_c - # NOT THREAD-SAFE + # Mutate following beamlet section in-place (confined to current beamlet instance) replace!(gauss, _interaction, i + 1) else # Valid new interaction, drop children and add new ray @@ -503,6 +572,9 @@ function trace_system!( end break end + if isnothing(_object) + break + end # Calculate interaction interaction = interact3d(system, _object, agb, seg_counter) if isnothing(interaction) @@ -556,28 +628,16 @@ function retrace_system!( # Iterate over chief rays for (i, c_ray) in enumerate(rays(agb.c)) - # Test if intersection is valid - _intersection = intersection(c_ray) - if isnothing(_intersection) - cleanup_children = true - cleanup_tail = true - reset_intersection = true - cutoff = i - break - end - # Recalculate current intersection (use shape of hint if available) + # Recalculate current intersection if isnothing(_hint) - _object = object(_intersection) - intersection!(c_ray, intersect3d(_object, c_ray)) + intersection!(c_ray, trace_all(system, c_ray)) for beam in aux - intersection!(rays(beam)[i], intersect3d(_object, rays(beam)[i])) + intersection!(rays(beam)[i], trace_all(system, rays(beam)[i])) end else - _object = object(_hint) - _shape = BeamletOptics.shape(_hint) - intersection!(c_ray, intersect3d(_shape, c_ray)) + intersection!(c_ray, trace_one(system, c_ray, _hint)) for beam in aux - intersection!(rays(beam)[i], intersect3d(_shape, rays(beam)[i])) + intersection!(rays(beam)[i], trace_one(system, rays(beam)[i], _hint)) end end # Test if all beams still hit the same target @@ -588,15 +648,16 @@ function retrace_system!( cutoff = i break end - # Test if valid intersection - if isnothing(intersection(c_ray)) + # Test if valid intersection and object + c_int = intersection(c_ray) + _object = isnothing(c_int) ? nothing : object(c_int) + if isnothing(_object) cleanup_children = true cleanup_tail = true reset_intersection = true cutoff = i break end - # Update object field object!(intersection(c_ray), _object) for beam in aux r_int = intersection(rays(beam)[i]) @@ -616,7 +677,7 @@ function retrace_system!( end # Update next beamlet section if i < n_c - # NOT THREAD-SAFE + # Mutate following beamlet section in-place (confined to current beamlet instance) replace!(agb, _interaction, i + 1) else # Valid new interaction, drop children and add new ray @@ -626,7 +687,9 @@ function retrace_system!( # Verify that the paraxial assumptions still hold for the new segment if check_invariant && !check_optical_invariant(agb, i + 1; threshold = threshold) + cleanup_children = true cleanup_tail = true + reset_intersection = true cutoff = i break end @@ -674,6 +737,7 @@ A maximum number of rays per `beam` (`r_max`) can be specified in order to avoid - `depth_max = get_default_depth_max()`: Maximum number of branching levels explored from the root beam. - `check_invariant = true`: enables or disables optical invariant checks where applicable - `threshold = get_invariant_threshold()`: threshold for paraxial invariant checks +- `power_cutoff = get_default_power_cutoff()`: power threshold below which sub-beams/split paths are dropped to prevent infinite branching (default: 0.0) """ function solve_system!( system::AbstractSystem, @@ -683,12 +747,20 @@ function solve_system!( retrace::Bool = true, depth_max::Int = get_default_depth_max(), check_invariant::Bool = true, - threshold::Real = get_invariant_threshold() + threshold::Real = get_invariant_threshold(), + power_cutoff::Real = get_default_power_cutoff() ) where {B <: AbstractBeam} queue = Tuple{B, Int}[(beam, 1)] - while !isempty(queue) - # Process beams in FIFO order. - current, depth = popfirst!(queue) + head = 1 + while head <= length(queue) + # Process beams in FIFO order without O(K) array shifts. + current, depth = queue[head] + head += 1 + # Check power cutoff before tracing the current beam. + if optical_power(current) < power_cutoff + _drop_beams!(current) + continue + end # Optionally retrace the current beam. if retrace retrace_system!(system, current; check_invariant, threshold) @@ -710,9 +782,16 @@ function solve_system!( return nothing end +""" + solve_system!(system::AbstractSystem, bg::AbstractBeamGroup; kwargs...) + +Solve an optical system for an entire [`AbstractBeamGroup`](@ref) in parallel across available Julia threads. +Each beam in the group is processed independently via `Threads.@spawn`. Detector hit logging is +safely synchronized via internal reentrant locks. +""" function solve_system!(system::AbstractSystem, bg::AbstractBeamGroup; kwargs...) - Threads.@threads for _beam in beams(bg) - solve_system!(system, _beam; kwargs...) + @sync for _beam in beams(bg) + Threads.@spawn solve_system!(system, _beam; kwargs...) end return nothing end diff --git a/src/Utils/LinearAlgebraUtils.jl b/src/Utils/LinearAlgebraUtils.jl index 0bd3d81f9..0b34cb3a5 100644 --- a/src/Utils/LinearAlgebraUtils.jl +++ b/src/Utils/LinearAlgebraUtils.jl @@ -3,8 +3,8 @@ Tests if `v1` is parallel to `v2`. """ -function isparallel3d(v1::AbstractArray, v2::AbstractArray) - return isapprox(abs(dot(normalize(v1), normalize(v2))), 1, atol=eps()) +function isparallel3d(v1::AbstractArray, v2::AbstractArray; atol=1e-8) + return isapprox(abs(dot(normalize(v1), normalize(v2))), 1; atol=atol) end """ @@ -102,9 +102,13 @@ function align3d(start::AbstractVector{A}, target::AbstractVector{B}) where {A, return SMatrix{3,3}(one(T)I) end if cosA ≈ -1 - return @SArray [-one(T) zero(T) zero(T); - zero(T) -one(T) zero(T); - zero(T) zero(T) one(T)] + u = normal3d(start) + ux, uy, uz = u + return @SArray [ + 2*ux^2-one(T) 2*ux*uy 2*ux*uz + 2*uy*ux 2*uy^2-one(T) 2*uy*uz + 2*uz*ux 2*uz*uy 2*uz^2-one(T) + ] end k = 1 / (1 + cosA) R = @SArray [ diff --git a/src/Utils/OpticUtils.jl b/src/Utils/OpticUtils.jl index 6bdc7e747..8a3d0f77b 100644 --- a/src/Utils/OpticUtils.jl +++ b/src/Utils/OpticUtils.jl @@ -28,12 +28,12 @@ If the critical angle for n1, n2 and the incident angle is reached, the ray is r - `n1`: index of ref. before refraction - `n2`: index of ref. after refraction """ -function refraction3d(dir::AbstractArray, normal::AbstractArray, n1::Real, n2::Real) +function refraction3d(dir::AbstractArray, normal::AbstractArray, n1::Number, n2::Number) # dir and normal must have unit length! isapprox(norm(dir), 1) || throw(ArgumentError("dir must have unit length")) isapprox(norm(normal), 1) || throw(ArgumentError(lazy"norm must have unit length: $(norm(normal))")) - n = n1 / n2 + n = real(n1) / real(n2) cosθi = -dot(normal, dir) sinθt² = n^2 * (1 - cosθi^2) # Check for total reflection @@ -52,7 +52,7 @@ If center of sphere is on left then R < 0. If center of sphere is on right then """ lensmakers_eq(R1, R2, n) = 1 / ((n - 1) * (1 / R1 - 1 / R2)) -rayleigh_range(λ, w0, M2, n = 1) = π * n * w0^2 / λ / M2 +rayleigh_range(λ, w0, M2 = 1, n = 1) = π * n * w0^2 / λ / M2 beam_waist(z, w0, zr) = w0 * sqrt(1 + (z / zr)^2) diff --git a/src/Utils/RefractiveIndexUtils.jl b/src/Utils/RefractiveIndexUtils.jl index ce71d3bad..ce082eac8 100644 --- a/src/Utils/RefractiveIndexUtils.jl +++ b/src/Utils/RefractiveIndexUtils.jl @@ -37,7 +37,7 @@ test_refractive_index_function(::DiscreteRefractiveIndex) = nothing test_refractive_index_function(input) Tests if `input` is callable with a single `Real` argument for the wavelength `λ` and -returns a single `Real` value for the refractive index `n`. +returns a single `Number` value (real or complex) for the refractive index `n`. """ function test_refractive_index_function(input) # Test function compat for the following types of λ @@ -46,13 +46,13 @@ function test_refractive_index_function(input) for T in Ts # Test if input accepts types answer = input(one(T)) - # Test if input returns single real value - if !isa(answer, Real) + # Test if input returns single number value (real or complex) + if !isa(answer, Number) error() end end catch - error_msg = "Ref. index must be callable with a single Real argument and return a single real result." + error_msg = "Ref. index must be callable with a single Real argument and return a single Number result." throw(ArgumentError(error_msg)) end return nothing @@ -97,6 +97,61 @@ function (SE::SellmeierEquation)(λ) return sqrt(n²) end +""" + AbsorbingMedium(n_real, α) + +A callable medium wrapper representing a material with real base refractive index `n_real` +and bulk linear absorption coefficient `α` in [1/m] (Lambert-Beer: ``I(L) = I_0 e^{-\\alpha L}``). +`n_real` and `α` can be constant numbers or functions of wavelength `λ -> n_real(λ)`, `λ -> α(λ)`. + +When called with wavelength `λ`, returns the complex refractive index: +```math +\\tilde{n}(\\lambda) = n_{\\mathrm{real}}(\\lambda) + i \\kappa(\\lambda) = n_{\\mathrm{real}}(\\lambda) + i \\frac{\\alpha(\\lambda) \\lambda}{4\\pi} +``` + +# Sign convention +Optics standard: ``\\tilde{n} = n + i\\kappa`` with ``\\kappa > 0`` for absorbing media (damping factor ``e^{-\\alpha L} = e^{-4\\pi \\kappa L / \\lambda}``). +""" +struct AbsorbingMedium{N, A} + n_real::N + alpha::A +end + +function (m::AbsorbingMedium)(λ::Real) + n_r = m.n_real isa Function ? real(m.n_real(λ)) : real(m.n_real) + α_val = m.alpha isa Function ? m.alpha(λ) : m.alpha + κ = (α_val * λ) / (4π) + return complex(n_r, κ) +end + +test_refractive_index_function(::AbsorbingMedium) = nothing + +""" + GainMedium(n_real, g) + +A callable medium wrapper representing an active laser gain material with real base refractive index `n_real` +and small-signal gain coefficient `g` in [1/m] (where `g > 0` amplifies power as ``I(L) = I_0 e^{+g L}``). +`n_real` and `g` can be constant numbers or functions of wavelength `λ -> n_real(λ)`, `λ -> g(λ)`. + +When called with wavelength `λ`, returns the complex refractive index: +```math +\\tilde{n}(\\lambda) = n_{\\mathrm{real}}(\\lambda) - i \\frac{g(\\lambda) \\lambda}{4\\pi} +``` +""" +struct GainMedium{N, G} + n_real::N + gain::G +end + +function (m::GainMedium)(λ::Real) + n_r = m.n_real isa Function ? real(m.n_real(λ)) : real(m.n_real) + g_val = m.gain isa Function ? m.gain(λ) : m.gain + κ = -(g_val * λ) / (4π) + return complex(n_r, κ) +end + +test_refractive_index_function(::GainMedium) = nothing + """ RefractiveIndex @@ -104,8 +159,57 @@ Union type that represents valid means to pass a refractive index `n` to e.g. [` The core assumption is that: 1. the refractive index is callable with a **single** `Number` argument `λ` to represent the wavelength in [m] -2. the return value is a **single** `Number` value for the refractive index +2. the return value is a **single** `Number` value (real or complex) for the refractive index + +Refer to e.g. [`DiscreteRefractiveIndex`](@ref), [`SellmeierEquation`](@ref), [`AbsorbingMedium`](@ref), and [`GainMedium`](@ref). +""" +const RefractiveIndex = Union{Function, DiscreteRefractiveIndex, SellmeierEquation, AbsorbingMedium, GainMedium} + +""" + real_refractive_index(n) + real_refractive_index(obj, λ) + +Returns the real part of the refractive index ``\\text{Re}(\\tilde{n})``. +""" +@inline real_refractive_index(n::Number) = real(n) +@inline real_refractive_index(obj, λ::Real) = real(refractive_index(obj, λ)) + +""" + extinction_coefficient(n) + extinction_coefficient(obj, λ) -Refer to e.g. [`DiscreteRefractiveIndex`](@ref). +Returns the imaginary part of the refractive index (extinction coefficient) ``\\kappa = \\text{Im}(\\tilde{n})``. """ -const RefractiveIndex = Union{Function, DiscreteRefractiveIndex, SellmeierEquation} \ No newline at end of file +@inline extinction_coefficient(n::Number) = imag(n) +@inline extinction_coefficient(obj, λ::Real) = imag(refractive_index(obj, λ)) + +""" + absorption_coefficient(n, λ) + absorption_coefficient(obj, λ) + +Returns the bulk linear absorption coefficient ``\\alpha = \\frac{4\\pi \\kappa}{\\lambda}`` in [1/m]. +Positive for absorbing media, negative for gain media. +""" +@inline absorption_coefficient(n::Number, λ::Real) = (4π * imag(n)) / λ +@inline absorption_coefficient(obj, λ::Real) = absorption_coefficient(refractive_index(obj, λ), λ) + +""" + bulk_attenuation_factor(n, λ, L) + +Computes the power and field attenuation factors `(att_power, att_field)` for light propagating +over physical path length `L` in a medium with refractive index `n` at wavelength `λ`. +- For non-absorbing media (``\\text{Im}(n) = 0``), returns `(1.0, 1.0)`. +- For absorbing media (``\\kappa = \\text{Im}(n) > 0``), ``\\text{att\\_power} = e^{-\\alpha L}`` and ``\\text{att\\_field} = e^{-\\frac{\\alpha}{2} L}``. +- For gain media (``\\kappa < 0``), ``\\text{att\\_power} = e^{+g L}`` and ``\\text{att\\_field} = e^{+\\frac{g}{2} L}``. +""" +@inline function bulk_attenuation_factor(n::Number, λ::Real, L::Real) + κ = imag(n) + if iszero(κ) + T = typeof(real(n) * L) + return (one(T), one(T)) + end + arg_field = -2π * κ * L / λ + att_field = exp(arg_field) + att_power = exp(2 * arg_field) + return (att_power, att_field) +end \ No newline at end of file diff --git a/test/TestAstigmaticGaussianBeamlet.jl b/test/TestAstigmaticGaussianBeamlet.jl index 47c2a8080..14342a700 100644 --- a/test/TestAstigmaticGaussianBeamlet.jl +++ b/test/TestAstigmaticGaussianBeamlet.jl @@ -59,6 +59,34 @@ const BMO = BeamletOptics @test norm(w2) ≈ w0 atol=1e-6 end + @testset "Rayleigh range" begin + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + rx, ry = BMO.rayleigh_range(beam) + expected_zr = π * w0^2 / λ0 + @test rx ≈ expected_zr atol=1e-6 + @test ry ≈ expected_zr atol=1e-6 + + rx2, ry2 = BMO.rayleigh_range(beam; M2=2.0) + @test rx2 ≈ expected_zr / 2.0 atol=1e-6 + @test ry2 ≈ expected_zr / 2.0 atol=1e-6 + end + + @testset "Batch and In-place Field Evaluation" begin + beam = AstigmaticGaussianBeamlet([0.0, 0, 0], [0, 1, 0], λ0, w0; E0=[0,0,1], support=[0,0,1]) + dir = normalize([0, 1, 0]) + ex = normalize(cross(dir, [0,0,1])) + z_eval = 0.05 + rs = [ex * r for r in LinRange(-2e-4, 2e-4, 11)] + + E_single = [BMO.parabasal_field(beam, r, z_eval) for r in rs] + E_batch = BMO.parabasal_field(beam, rs, z_eval) + @test E_batch ≈ E_single + + E_out = zeros(ComplexF64, size(rs)) + BMO.electric_field!(E_out, beam, rs, z_eval) + @test E_out ≈ E_single + end + @testset "Waist parameters with offsets" begin z0_x = 0.05 z0_y = 0.10 diff --git a/test/TestBugFixes.jl b/test/TestBugFixes.jl index 0629421e5..a4744fd5c 100644 --- a/test/TestBugFixes.jl +++ b/test/TestBugFixes.jl @@ -229,4 +229,82 @@ end @test all(==(lengths[1]), lengths) end +@testset "Coincident refractive-reflective boundary" begin + # Test for coincident boundary bug where a mirror placed exactly at the lens/glass back boundary + # is correctly processed and reflects rays instead of letting them leak/refract straight through. + + λ = 354.84e-9 + B1, B2, B3 = 0.6961663, 0.4079426, 0.8974794 + C1, C2, C3 = 0.0684043^2, 0.1162414^2, 9.896161^2 + SE = SellmeierEquation(B1, B2, B3, C1, C2, C3) + + d_glass = 17.5mm + L_bs = 30mm + + # Lens element (glass block) + glass_block = Lens(RectangularFlatSurface(L_bs), RectangularFlatSurface(L_bs), d_glass, SE) + translate3d!(glass_block, [0.0, L_bs/2, 0.0]) + + # Mirror placed EXACTLY at the back face of the glass block (no gap, gap = 0.0) + mirror = SquarePlanoMirror(L_bs, 5mm) + translate3d!(mirror, [0.0, L_bs/2 + d_glass, 0.0]) + + # Detector placed to capture the returning reflected ray + detector = Detector(16mm) + translate3d!(detector, [0.0, -10mm, 0.0]) + + # Beam pointing along +y, starting at y = 10 mm + beam = GaussianBeamlet([0.0, 10mm, 0.0], [0.0, 1.0, 0.0], λ, 0.5mm) + + system = System([glass_block, mirror, detector]) + + empty!(detector) + solve_system!(system, beam) + + @test detector.hits !== nothing + @test length(detector.hits) == 1 +end + +@testset "Auxiliary beamlet TIR before splitting" begin + struct Splitting5050Coating end + BMO.coating_behavior(::Splitting5050Coating, ray) = Splitting() + BMO.get_jones_matrix(::Splitting5050Coating, θi, λ, n1, n2, is_reflected; from_front=true) = BMO.SPBasis(1/sqrt(2), 0, 0, 1/sqrt(2)) + + mesh = BMO.QuadraticFlatMesh(100mm) + coating = Coating(mesh, Splitting5050Coating(), normal_filter=[0.0, -1.0, 0.0]) + + # Ray incident from n_incident = 1.5 to n_transmitted = 1.0 (glass to air) + # Critical angle = asin(1/1.5) ≈ 41.8103 deg + # Chief ray angle = 41.7 deg (refracts, near critical angle) + θ = deg2rad(41.7) + dir_c = [sin(θ), cos(θ), 0.0] + + # Waist size 0.001mm (1 um) gives divergence angle large enough for divergence ray to exceed critical angle + w0 = 0.001mm + λ = 1000e-9 + + gauss = GaussianBeamlet([0.0, -10mm, 0.0], dir_c, λ, w0) + + n_inc = 1.5 + n_trans = 1.0 + normal = [0.0, -1.0, 0.0] + + tir_triggered = false + cb = () -> (tir_triggered = true; return nothing) + + BMO._propagate_splitting_gaussian_beamlet( + System([coating]), coating, Splitting5050Coating(), gauss, 1, n_inc, n_trans, normal, true, cb + ) + @test tir_triggered + + agb = AstigmaticGaussianBeamlet([0.0, -10mm, 0.0], dir_c, λ, w0) + tir_triggered_agb = false + cb_agb = () -> (tir_triggered_agb = true; return nothing) + + BMO._propagate_splitting_astigmatic_beamlet( + System([coating]), coating, Splitting5050Coating(), agb, 1, n_inc, n_trans, normal, true, cb_agb + ) + @test tir_triggered_agb +end + end # MODULE diff --git a/test/TestGaussianBeamlet.jl b/test/TestGaussianBeamlet.jl index 10175c7a2..59365782e 100644 --- a/test/TestGaussianBeamlet.jl +++ b/test/TestGaussianBeamlet.jl @@ -158,6 +158,19 @@ const mm = 1e-3 @test BMO.istilted(system, gauss) == true @test BMO.isparaxial(system, gauss, deg2rad(30)) == false end + + @testset "Batch and In-place Field Evaluation" begin + gauss_test = GaussianBeamlet([0.0, 0, 0], [0, 1, 0], 1064e-9, 1e-3) + rs = LinRange(-5e-4, 5e-4, 11) + z_eval = 0.05 + E_single = [BMO.electric_field(gauss_test, r, z_eval) for r in rs] + E_batch = BMO.electric_field(gauss_test, rs, z_eval) + @test E_batch ≈ E_single + + E_out = zeros(ComplexF64, size(rs)) + BMO.electric_field!(E_out, gauss_test, rs, z_eval) + @test E_out ≈ E_single + end end end diff --git a/test/TestSystem.jl b/test/TestSystem.jl index 84254ee2b..23670f6d8 100644 --- a/test/TestSystem.jl +++ b/test/TestSystem.jl @@ -101,11 +101,18 @@ const BMO = BeamletOptics system = System(mirrors) first_ray = Ray(origin, dir) beam = Beam(first_ray) - t1 = @timed BMO.trace_system!(system, beam, r_max = 1000000) - t2 = @timed BMO.retrace_system!(system, beam) # for precompilation - t2 = @timed BMO.retrace_system!(system, beam) - if t1.time < t2.time - @warn "Retracing took longer than tracing, something might be bugged...\n Tracing: $(t1.time) s\n Retracing: $(t2.time) s" + + # Warmup + BMO.trace_system!(system, beam, r_max = 1000000) + BMO.retrace_system!(system, beam) + + # Benchmark minimum execution times over iterations to eliminate OS scheduling jitter + N_bench = 20 + t1_min = minimum(ntuple(_ -> (@timed BMO.trace_system!(system, Beam(Ray(origin, dir)), r_max = 1000000)).time, N_bench)) + t2_min = minimum(ntuple(_ -> (@timed BMO.retrace_system!(system, beam)).time, N_bench)) + + if t1_min < t2_min + @warn "Retracing took longer than tracing, something might be bugged...\n Tracing: $(t1_min) s\n Retracing: $(t2_min) s" end end end diff --git a/test/TestUtils.jl b/test/TestUtils.jl index 85055846c..61b7362fc 100644 --- a/test/TestUtils.jl +++ b/test/TestUtils.jl @@ -55,10 +55,12 @@ const BMO = BeamletOptics target = [1, 0, 0] T = BMO.align3d(start, target) @test T * start ≈ target - # Test parallel opposite case - target = [-1, 0, 0] - T = BMO.align3d(start, target) - @test T * start ≈ target + # Test parallel opposite cases (X, Y, Z axes and arbitrary 3D direction) + for s_vec in ([1, 0, 0], [0, 1, 0], [0, 0, 1], normalize([1, 2, 3])) + T_opp = BMO.align3d(s_vec, -s_vec) + @test T_opp * s_vec ≈ -s_vec + @test det(T_opp) ≈ 1 + end # Test norm and 45° rotation target = [1.0, 1.0, 0.0] T = BMO.align3d(start, target) From 56aae836407ac3f580c42052f6c672204cccfefc Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 06:58:34 +0200 Subject: [PATCH 6/7] feat(coatings): modern surface coating architecture, component refactoring, and Makie visualization --- .github/workflows/CI.yml | 4 +- docs/DocUtils.jl | 33 +- docs/make.jl | 106 ++- docs/src/api/geometry.md | 26 +- docs/src/api/sdfs.md | 29 +- docs/src/basics/beams/stigmatic_beam.md | 3 + docs/src/basics/components/coatings.md | 161 ++++ docs/src/basics/components/components.md | 2 +- docs/src/basics/components/lenses.md | 6 + docs/src/basics/components/materials.md | 152 +++ docs/src/basics/components/mirrors.md | 4 + docs/src/basics/components/polarizers.md | 41 +- docs/src/basics/rays.md | 14 +- docs/src/examples/coatings.md | 182 ++++ docs/src/examples/polarizing_optics.md | 109 +++ docs/src/refs.bib | 14 + docs/src/tutorials/fabry_perot.md | 158 ++++ docs/src/tutorials/wolit_trap.md | 160 ++++ ext/BeamletOpticsMakieExt.jl | 3 +- ext/RenderObjects.jl | 36 + ext/RenderPresets.jl | 13 +- ext/RenderSDF.jl | 6 +- .../Beamsplitters/Beamsplitters.jl | 2 + .../Beamsplitters/CubeBeamsplitter.jl | 115 +-- .../Beamsplitters/PlateBeamsplitter.jl | 330 ++----- .../Beamsplitters/PolarizingBeamSplitter.jl | 129 +++ .../PolarizingCubeBeamsplitter.jl | 55 ++ .../Beamsplitters/ThinBeamsplitter.jl | 233 +---- src/OpticalComponents/Detectors/Detector.jl | 9 +- .../Detectors/DetectorUtils.jl | 16 +- .../Detectors/FieldCalculation.jl | 112 ++- src/OpticalComponents/DoubletLenses.jl | 67 +- src/OpticalComponents/Lenses.jl | 103 +-- src/OpticalComponents/Mirrors.jl | 115 +-- src/OpticalComponents/Misc.jl | 18 +- .../Polarizers/PolarizationFilter.jl | 79 +- src/OpticalComponents/Polarizers/Waveplate.jl | 209 +++++ src/OpticalComponents/Prisms.jl | 7 +- src/Workloads/coatings_wl.jl | 28 + src/Workloads/precompile.jl | 1 + test/Components/TestBeamsplitters.jl | 26 +- test/Components/TestBulkAbsorption.jl | 150 +++ test/Components/TestCoatings.jl | 864 ++++++++++++++++++ test/Components/TestPolarizers.jl | 386 +++++++- .../Components/TestPolarizingBeamsplitters.jl | 151 +++ test/E2E/TestMachZehnder.jl | 4 +- test/E2E/TestMichelson.jl | 4 +- test/Lenses/TestSphericalLenses.jl | 9 + test/TestMisc.jl | 4 +- test/runtests.jl | 3 + 50 files changed, 3534 insertions(+), 957 deletions(-) create mode 100644 docs/src/basics/components/coatings.md create mode 100644 docs/src/basics/components/materials.md create mode 100644 docs/src/examples/coatings.md create mode 100644 docs/src/examples/polarizing_optics.md create mode 100644 docs/src/tutorials/fabry_perot.md create mode 100644 docs/src/tutorials/wolit_trap.md create mode 100644 src/OpticalComponents/Beamsplitters/PolarizingBeamSplitter.jl create mode 100644 src/OpticalComponents/Beamsplitters/PolarizingCubeBeamsplitter.jl create mode 100644 src/OpticalComponents/Polarizers/Waveplate.jl create mode 100644 src/Workloads/coatings_wl.jl create mode 100644 test/Components/TestBulkAbsorption.jl create mode 100644 test/Components/TestCoatings.jl create mode 100644 test/Components/TestPolarizingBeamsplitters.jl diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 5dba9733b..657e41d31 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -31,7 +31,7 @@ jobs: arch: - x64 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 with: version: ${{ matrix.version }} @@ -53,7 +53,7 @@ jobs: contents: write statuses: write steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 with: version: '1' diff --git a/docs/DocUtils.jl b/docs/DocUtils.jl index 5ef8a8999..89e775a00 100644 --- a/docs/DocUtils.jl +++ b/docs/DocUtils.jl @@ -10,22 +10,23 @@ const GLOBAL_USE_PLACEHOLDERS = true This is a function to speed up compilation time when building the docs locally. It checks whether the `include` call is made locally or from within the **CI environment**. -In the former case, script evaluation is avoided and a placeholder figure is created for +In the former case, script evaluation is avoided and a placeholder figure is created for each `save` call within the script. Evaluation can be forced by setting `use_placeholder = false`. Global evaluation can be forced by setting `GLOBAL_USE_PLACEHOLDERS = false` in this file (does not apply for CI env.). """ -function conditional_include(fname::String; use_placeholder::Bool=!haskey(ENV, "CI")) +function conditional_include(fname::String; use_placeholder::Bool = !haskey(ENV, "CI")) # Check for global flag if not within CI env. if !haskey(ENV, "CI") && !GLOBAL_USE_PLACEHOLDERS use_placeholder = false end # Check if to run script - if use_placeholder + if use_placeholder content = read(fname, String) # match save("filename") but ignore comments, i.e. # save(...) - pattern = Regex("^[ \\t]*save\\(\\s*\"([^\"]+)\"\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)", "m") + pattern = Regex( + "^[ \\t]*save\\(\\s*\"([^\"]+)\"\\s*,\\s*([a-zA-Z_][a-zA-Z0-9_]*)", "m") for match in eachmatch(pattern, content) save_name = match.captures[1] fig_name = match.captures[2] @@ -36,22 +37,22 @@ function conditional_include(fname::String; use_placeholder::Bool=!haskey(ENV, " matches = collect(eachmatch(npattern, prior_content)) if !isempty(matches) nmatch = last(matches) - _width = parse(Int, nmatch.captures[1]) + _width = parse(Int, nmatch.captures[1]) _height = parse(Int, nmatch.captures[2]) else @info "Using default height for $fig_name" - _width = 600 + _width = 600 _height = 300 end # save placeholder - fig = Figure(size=(_width, _height)) - ax = Axis(fig[1,1], backgroundcolor=:gray) + fig = Figure(size = (_width, _height)) + ax = Axis(fig[1, 1], backgroundcolor = :gray) hidedecorations!(ax) text!(ax, 0, 0; - text="$save_name\n($_width x $_height)", - align=(:center, :center), - color=:white, - fontsize=20 + text = "$save_name\n($_width x $_height)", + align = (:center, :center), + color = :white, + fontsize = 20 ) save(save_name, fig) @info "Saving placeholder for $save_name (Size: $_width x $_height, fig_var_name=$fig_name)" @@ -68,7 +69,7 @@ end function replace_build_with_src(path::String) clean_path = abspath(path) build_segment = joinpath("docs", "build") - src_segment = joinpath("docs", "src") + src_segment = joinpath("docs", "src") src_path = replace(clean_path, build_segment => src_segment) return src_path end @@ -79,7 +80,7 @@ end This function runs the build script and places the images within the docs\\src folder when run outside of the CI/CD pipeline. It is recommended to use this approach when the rendered image is too computationally intensive for the github runner. If a prerendered image already exists, it has to be **deleted manually** in order to trigger a re-run. - + # Arguments - `fname`: points to the BMO render script @@ -120,9 +121,9 @@ function prerender_include(fname::String, cname::String) save_name = match.captures[1] path_name = dirname(cname) @info "Copying $save_name from \\build to \\src" - cp(joinpath(path_name, save_name), joinpath(location, save_name); force=true) + cp(joinpath(path_name, save_name), joinpath(location, save_name); force = true) end return nothing end -end \ No newline at end of file +end diff --git a/docs/make.jl b/docs/make.jl index bf6f0d371..9575421a4 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -10,83 +10,89 @@ DocMeta.setdocmeta!( BeamletOptics, :DocTestSetup, :(using BeamletOptics); - recursive=true + recursive = true ) bib = CitationBibliography(joinpath(@__DIR__, "src", "refs.bib")) makedocs(; - modules=[BeamletOptics], - authors="Hugo Uittenbosch , Oliver Kliebisch and contributors", - sitename="BeamletOptics.jl", - format=Documenter.HTML(; - prettyurls=get(ENV, "CI", "false") == "true", - canonical="https://JuliaPhysics.github.io/BeamletOptics.jl", - edit_link="master", - assets=String[], - size_threshold_ignore=["reference.md"], - sidebar_sitename = false, + modules = [BeamletOptics], + authors = "Hugo Uittenbosch , Oliver Kliebisch and contributors", + sitename = "BeamletOptics.jl", + format = Documenter.HTML(; + prettyurls = get(ENV, "CI", "false") == "true", + canonical = "https://JuliaPhysics.github.io/BeamletOptics.jl", + edit_link = "master", + assets = String[], + size_threshold_ignore = ["reference.md"], + sidebar_sitename = false ), - pagesonly=true, - pages=[ + pagesonly = true, + pages = [ "Home" => "index.md", "Getting started" => Any[ "Tutorials" => Any[ - "Beam expander" => joinpath("tutorials", "expander.md"), - "Miniature microscope" => joinpath("tutorials", "microscope.md"), - "Michelson interferometer" => joinpath("tutorials", "michelson.md"), + "Beam expander" => joinpath("tutorials", "expander.md"), + "Miniature microscope" => joinpath("tutorials", "microscope.md"), + "Michelson interferometer" => joinpath("tutorials", "michelson.md"), + "Wedge trap" => joinpath("tutorials", "wolit_trap.md"), + "Fabry-Pérot cavity" => joinpath("tutorials", "fabry_perot.md") ], "Examples" => Any[ - "Spherical lenses" => joinpath("examples", "spherical_lenses.md"), - "Aspherical lenses" => joinpath("examples", "aspherical_lenses.md"), - "Double Gauss lens" => joinpath("examples", "double_gauss.md"), - "Lens groups" => joinpath("examples", "lens_groups.md"), - "Double slit" => joinpath("examples", "double_slit.md"), - ], + "Spherical lenses" => joinpath("examples", "spherical_lenses.md"), + "Aspherical lenses" => joinpath("examples", "aspherical_lenses.md"), + "Double Gauss lens" => joinpath("examples", "double_gauss.md"), + "Lens groups" => joinpath("examples", "lens_groups.md"), + "Double slit" => joinpath("examples", "double_slit.md"), + "Optical coatings" => joinpath("examples", "coatings.md"), + "Polarizing optics" => joinpath("examples", "polarizing_optics.md") + ] ], "Basics" => Any[ - "Introduction" => joinpath("basics", "intro.md"), - "Rays" => joinpath("basics", "rays.md"), + "Introduction" => joinpath("basics", "intro.md"), + "Rays" => joinpath("basics", "rays.md"), "Beams" => Any[ - "Basic beam" => joinpath("basics", "beams", "beams.md"), - "Stigmatic Gaussian" => joinpath("basics", "beams", "stigmatic_beam.md"), - "Astigmatic Gaussian" => joinpath("basics", "beams", "astigmatic_beam.md"), - "Beam groups" => joinpath("basics", "beams", "beam_groups.md"), + "Basic beam" => joinpath("basics", "beams", "beams.md"), + "Stigmatic Gaussian" => joinpath("basics", "beams", "stigmatic_beam.md"), + "Astigmatic Gaussian" => joinpath("basics", "beams", "astigmatic_beam.md"), + "Beam groups" => joinpath("basics", "beams", "beam_groups.md") ], "Optical components" => Any[ - "Overview" => joinpath("basics", "components", "components.md"), - "Mirrors" => joinpath("basics", "components", "mirrors.md"), - "Lenses" => joinpath("basics", "components", "lenses.md"), - "Beamsplitters" => joinpath("basics", "components", "beamsplitters.md"), - "Detectors" => joinpath("basics", "components", "detectors.md"), - "Polarizing components" => joinpath("basics", "components", "polarizers.md"), + "Overview" => joinpath("basics", "components", "components.md"), + "Mirrors" => joinpath("basics", "components", "mirrors.md"), + "Lenses" => joinpath("basics", "components", "lenses.md"), + "Beamsplitters" => joinpath("basics", "components", "beamsplitters.md"), + "Detectors" => joinpath("basics", "components", "detectors.md"), + "Polarizing components" => joinpath("basics", "components", "polarizers.md"), + "Coatings" => joinpath("basics", "components", "coatings.md"), + "Materials & Absorption" => joinpath("basics", "components", "materials.md") ], - "Optical systems" => joinpath("basics", "systems.md"), - "Visualization" => joinpath("basics", "render.md"), + "Optical systems" => joinpath("basics", "systems.md"), + "Visualization" => joinpath("basics", "render.md") ], "Developer Documentation" => Any[ "Developer guide" => Any[ - "Contributing" => joinpath("api", "contribute.md"), - "Documentation development" => joinpath("api", "docdev.md"), + "Contributing" => joinpath("api", "contribute.md"), + "Documentation development" => joinpath("api", "docdev.md") ], "API design" => Any[ - "Introduction" => joinpath("api", "api.md"), - "Conventions" => joinpath("api", "conventions.md"), - "Core design" => joinpath("api", "core.md"), + "Introduction" => joinpath("api", "api.md"), + "Conventions" => joinpath("api", "conventions.md"), + "Core design" => joinpath("api", "core.md"), "Geometry" => Any[ - "Geometry representation" => joinpath("api", "geometry.md"), - "Meshes" => joinpath("api", "meshes.md"), - "SDFs" => joinpath("api", "sdfs.md"), - ], - ], + "Geometry representation" => joinpath("api", "geometry.md"), + "Meshes" => joinpath("api", "meshes.md"), + "SDFs" => joinpath("api", "sdfs.md") + ] + ] ], "Reference" => "reference.md" ], - plugins=[bib], + plugins = [bib] ) deploydocs(; - repo="github.com/JuliaPhysics/BeamletOptics.jl.git", - devbranch="master", - push_preview=false, + repo = "github.com/JuliaPhysics/BeamletOptics.jl.git", + devbranch = "master", + push_preview = false ) diff --git a/docs/src/api/geometry.md b/docs/src/api/geometry.md index 7102f4fe7..de1a338a7 100644 --- a/docs/src/api/geometry.md +++ b/docs/src/api/geometry.md @@ -23,4 +23,28 @@ An `AbstractObject` can consist of multiple `AbstractShape`s or even multiple su ```@docs; canonical=false BeamletOptics.SingleShape BeamletOptics.MultiShape -``` \ No newline at end of file +``` + +--- + +## Face Partitioning & Coordinate Transformation + +When custom components need to apply selective properties (such as coatings or specific surface behaviors) to different parts of their geometry, the **Face Partitioning API** is used. + +### Coordinate Transformation + +To determine where an intersection occurred relative to the local reference frame of a shape, BMO uses `world_to_local`: + +```@docs; canonical=false +BeamletOptics.world_to_local +``` + +### Face Identification + +To partition the surface normal space of a shape into named faces (e.g., `:front`, `:back`, `:side`, or `:hypotenuse`), custom shapes override `face_id`: + +```@docs; canonical=false +BeamletOptics.face_id +``` + +By default, the fallback implementation assumes that the optical axis is aligned with the `y`-axis and partitions normal space into `:front` ($n_y < -0.1$), `:back` ($n_y > 0.1$), and `:side` otherwise. Subtypes representing prisms or custom geometries should implement specialized methods to identify faces (e.g., `RightAnglePrismSDF` maps normals to `:hypotenuse`, `:leg1`, `:leg2`, `:zpos`, `:zneg`). \ No newline at end of file diff --git a/docs/src/api/sdfs.md b/docs/src/api/sdfs.md index d5d84f0c8..f19e7b235 100644 --- a/docs/src/api/sdfs.md +++ b/docs/src/api/sdfs.md @@ -47,4 +47,31 @@ BeamletOptics.UnionSDF ``` !!! info - Since two exact SDFs will only yield an exact union during boolean addition, only the `+` operator is defined. Introducing the `-` operator is still under consideration. \ No newline at end of file + Since two exact SDFs will only yield an exact union during boolean addition, only the `+` operator is defined. Introducing the `-` operator is still under consideration. + +--- + +## Developer Guide: Implementing Custom SDFs + +When implementing a custom subtype `MySDF <: AbstractSDF`: + +1. **Required Interface**: + - `sdf(s::MySDF, point)`: returns the scalar distance to the surface. + - `bounding_sphere(s::MySDF)`: returns `(center, radius)`. + +2. **Analytic Normals (`normal3d`)**: + By default, `normal3d(s, pos)` falls back to finite-difference gradient sampling (`normal_fd`). + For maximum ray-tracing performance, overload `normal3d` with an exact analytical vector function whenever possible: + ```julia + function normal3d(s::MySDF, pos) + # return normalized normal vector in world coordinates + end + ``` + +3. **Symbolic Surface Tags (`surface_tag`)**: + To support fast face-selective coating matching (e.g. `:front`, `:back`, `:side`, `:top`, `:bottom`), overload `surface_tag`: + ```julia + function surface_tag(s::MySDF, point, normal) + # return :front, :back, :side, etc. based on local coordinates + end + ``` \ No newline at end of file diff --git a/docs/src/basics/beams/stigmatic_beam.md b/docs/src/basics/beams/stigmatic_beam.md index 646f5933f..25392f76a 100644 --- a/docs/src/basics/beams/stigmatic_beam.md +++ b/docs/src/basics/beams/stigmatic_beam.md @@ -46,6 +46,9 @@ The [`GaussianBeamlet`](@ref) implements the [`BeamletOptics.AbstractBeam`](@ref GaussianBeamlet ``` +!!! warning "Scalar Nature & Polarization Limitations" + The basic `GaussianBeamlet` is a **scalar** wave approximation. When interacting with optical coatings, it tracks scalar diagonal amplitude transmission ($J_{1,1}$). For optical setups involving polarizing optics (e.g. waveplates, polarizing beamsplitters, or rotated birefringent elements with cross-polarization $J_{1,2} \neq 0$), use [`AstigmaticGaussianBeamlet`](@ref) or [`PolarizedRay`](@ref), which provide full 3D vectorial Jones calculus tracking. + A [`GaussianBeamlet`](@ref) can be constructed via: ```@docs; canonical=false diff --git a/docs/src/basics/components/coatings.md b/docs/src/basics/components/coatings.md new file mode 100644 index 000000000..f0324e21e --- /dev/null +++ b/docs/src/basics/components/coatings.md @@ -0,0 +1,161 @@ +# Coatings + +In `BeamletOptics.jl`, coatings are physical models attached to optical boundaries. They modify the complex amplitude and polarization state of propagated rays and beamlets (such as `PolarizedRay` or `AstigmaticGaussianBeamlet`) according to their physical structure. + +The coatings system is designed around a clean separation between **geometry** (the shape of a lens, mirror, or flat interface) and **physics** (how light interacts with the boundary). + +--- + +## Coating Behaviors + +Every coating has an associated `CoatingBehavior` trait. The core ray-tracing engine uses this trait to determine the control flow of the ray propagation (e.g., whether a ray transmits, reflects, or splits): + +* **`Transmissive`**: Light is refracted through the interface into the adjacent medium. (Default for `Uncoated`, `SimpleARCoating`). +* **`Reflective`**: Light is reflected back into the incident medium. (Default for `SimpleHRCoating`). +* **`Splitting`**: The incident ray is explicitly split into both a transmitted ray and a reflected ray. (Default for `SimpleBeamsplitterCoating`, or when modeling beamsplitter interfaces). +* **`Absorptive`**: Light is immediately absorbed (terminated) at the interface, generating no child rays or beamlets. + +### Custom / Dynamic Coating Behaviors + +By default, the core engine retrieves the behavior trait of a coating statically by calling `coating_behavior(coating)`. However, developers can implement custom and dynamic behaviors by overloading the two-argument version: + +```julia +BeamletOptics.coating_behavior(coating::MyCustomCoating, ray::AbstractRay) +``` + +This allows a coating to dynamically change its behavior (e.g., switching from `Transmissive()` to `Reflective()` or `Splitting()`) on-the-fly based on properties of the incident ray—such as its angle of incidence, wavelength, or polarization state. + +For example, a custom wavelength-selective coating could be implemented as: +```julia +function BeamletOptics.coating_behavior(coating::MyFilter, ray::AbstractRay) + if wavelength(ray) < 600e-9 + return Reflective() + else + return Transmissive() + end +end +``` + +--- + + +## Available Coating Models + +`BeamletOptics.jl` provides several built-in coating models, ranging from idealized parameters to exact physical wave-propagation models: + +### Uncoated +Represents a bare interface between two media. The Fresnel transmission and reflection coefficients are computed dynamically based on the angle of incidence and the refractive indices of the adjacent media. +```@docs; canonical=false +BeamletOptics.Uncoated +``` + +### Simple AR / HR Coating +Idealized anti-reflective (AR) or highly-reflective (HR) coatings defined by a constant power reflectance $R$. +```@docs; canonical=false +BeamletOptics.SimpleARCoating +BeamletOptics.SimpleHRCoating +``` + +### Simple Beamsplitter Coating +An idealized splitting coating defined by constant complex amplitude coefficients for reflection ($r_s, r_p$) and transmission ($t_s, t_p$). +```@docs; canonical=false +BeamletOptics.SimpleBeamsplitterCoating +``` + +### Jones Coating +A generalized polarizing and phase-shifting boundary model defined by custom Jones matrices for transmission and reflection. The matrices can be static or functions of wavelength $\lambda$. + +!!! note "Optical Impedance & Power Conservation" + When light transmits across an index boundary with $n_1 \neq n_2$, `JonesCoating` and `SimpleBeamsplitterCoating` scale the transmitted field amplitude by the boundary impedance factor $\sqrt{\frac{n_1 \cos\theta_i}{n_2 \cos\theta_t}}$. This guarantees that ray intensity $|\mathbf{E}|^2$ strictly corresponds to optical power (conserving total Poynting flux across media with different refractive indices). +```@docs; canonical=false +BeamletOptics.JonesCoating +``` + +### Thin-Film Interference Coating +A physical multi-layer thin-film stack defined by a vector of refractive indices $n_j(\lambda)$ (which can be complex to model absorbing/metallic media) and physical thicknesses $d_j$. It calculates exact amplitude and phase coefficients using the **characteristic transfer matrix method**. +```@docs; canonical=false +BeamletOptics.ThinFilmCoating +``` + +### Graded Thin-Film Coating +A spatially graded thin-film coating where layer thicknesses vary across the surface according to a spatial scaling function `thickness_func(local_p)` at local hit point `local_p`. +```@docs; canonical=false +BeamletOptics.GradedThinFilmCoating +``` + +### Composite Surface Model +Composes multiple surface physics models sequentially. Reflection and transmission Jones matrices are multiplied across sub-models. +```@docs; canonical=false +BeamletOptics.CompositeSurfaceModel +``` + +--- + +## Applying Coatings to Components + +You can attach coatings natively to optical components (like lenses or mirrors) using the `with_coatings` API or by passing `coatings` when constructing the component. + +```@docs; canonical=false +BeamletOptics.with_coatings +BeamletOptics.coatings +``` + +### Face-Selective Coating +When coating a lens or prism, you can target specific faces by passing a `Pair` containing a filter pattern and the coating model. + +The filter pattern can be: +* A `Symbol` representing a named face of the shape (e.g., `:front`, `:back`, `:side` for rotationally symmetric lenses, or `:hypotenuse`, `:leg1`, `:leg2` for a `RightAnglePrism`). +* A `Tuple` or `Set` of `Symbol`s targeting multiple faces at once (e.g., `(:front, :back) => SimpleARCoating()`). +* An orientation vector (`AbstractVector`), matching faces whose local normal vector has a positive dot product with the orientation vector. +* A spatial predicate function `(local_pos, local_normal) -> Bool`. + +#### Examples +```julia +# Coat both front and back of a lens in one selector +coated_lens = lens |> with_coatings((:front, :back) => SimpleARCoating()) + +# Coat the hypotenuse of a prism with HR, and Leg 1 with AR +coated_prism = with_coatings(prism, :hypotenuse => SimpleHRCoating(), :leg1 => SimpleARCoating()) + +# Deepcopy shape when coating to avoid mutating shared inner shape instances +isolated_coated_lens = with_coatings(lens, :front => SimpleARCoating(); deepcopy_shape = true) +``` + +--- + +## Standalone Coatings + +If you want to represent a thin, free-floating coated interface (such as a flat filter or beam-splitting window) without wrapping a bulk refractive optic, you can use the standalone `Coating` component. This wraps a flat 2D shape and a coating model. + +```@docs; canonical=false +BeamletOptics.Coating +``` + +--- + +## Supporting Coatings in Custom Components (Developer Guide) + +If you are developing a custom optical component type `MyOptic <: AbstractObject` and want it to natively support coatings via `with_coatings`, follow these steps: + +1. **Include a `coatings` field in your struct**: + Parametrize the struct with `coatings::C` (defaulting to `()`), where `C <: Tuple`. + ```julia + struct MyOptic{T, S, C <: Tuple} <: AbstractRefractiveOptic{T} + shape::S + coatings::C + end + ``` + +2. **Implement `_attach_coatings`**: + Define `_attach_coatings` for your component type to construct a new instance with the updated coating tuple. Support the `deepcopy_shape` keyword argument: + ```julia + function BeamletOptics._attach_coatings(optic::MyOptic, new_coatings::Tuple; deepcopy_shape::Bool = false) + shape_inst = deepcopy_shape ? deepcopy(optic.shape) : optic.shape + return MyOptic(shape_inst, new_coatings) + end + ``` + Once `_attach_coatings` is defined, `with_coatings(optic, ...)` and `coatings(optic)` work automatically out-of-the-box! + +3. **Ray Interaction Dispatch**: + If your component inherits from `AbstractRefractiveOptic` or `AbstractReflectiveOptic`, the core ray-tracing engine automatically resolves active coatings via `resolve_coated_boundary` during ray-tracing without requiring any custom `interact3d` code. + diff --git a/docs/src/basics/components/components.md b/docs/src/basics/components/components.md index 63801ce4e..013e65ff3 100644 --- a/docs/src/basics/components/components.md +++ b/docs/src/basics/components/components.md @@ -5,7 +5,7 @@ Optical elements serve as the building blocks for optical systems in the context ## Component overview ```@contents -Pages = ["mirrors.md", "lenses.md", "beamsplitters.md", "detectors.md", "polarizers.md"] +Pages = ["mirrors.md", "lenses.md", "beamsplitters.md", "detectors.md", "polarizers.md", "coatings.md", "materials.md"] Depth = 2 ``` diff --git a/docs/src/basics/components/lenses.md b/docs/src/basics/components/lenses.md index a7f34e874..84bc1c84d 100644 --- a/docs/src/basics/components/lenses.md +++ b/docs/src/basics/components/lenses.md @@ -31,6 +31,12 @@ In practice, a great variety and mixture of different lens shapes exists -- e.g. Refer to the specific documentation or enter e.g. `? Lens` into the REPL to learn more about the constructors and their interfaces, as well as sign definitions and so on. +!!! tip "Coated Lenses" + To model lenses with customized reflective or anti-reflective boundaries (such as AR coatings on the front/back faces), refer to the [Coatings](@ref) section. You can construct a coated lens using the `with_coatings` API (e.g. `lens |> with_coatings(front = SimpleARCoating(0.01))`). + +!!! tip "Absorbing Lenses and Gain Media" + Lenses can be made from absorbing materials (e.g. absorption filters) or active gain crystals (e.g. laser rods) by providing an [`AbsorbingMedium`](@ref), [`GainMedium`](@ref), or complex refractive index function `λ -> complex(n, κ)`. See the [Materials, Absorption & Gain](@ref) section for details. + ### Surface based lens construction To make it easier to specify lenses similar to established optical simulation frameworks, e.g. [Zemax](https://www.ansys.com/products/optics/ansys-zemax-opticstudio), the [`BeamletOptics.AbstractSurface`](@ref) API can be used. This is a helper interface for surfaces specifications and interprets them to the corresponding SDF-based volume representation. diff --git a/docs/src/basics/components/materials.md b/docs/src/basics/components/materials.md new file mode 100644 index 000000000..8045bfe59 --- /dev/null +++ b/docs/src/basics/components/materials.md @@ -0,0 +1,152 @@ +# Materials, Absorption & Gain + +In `BeamletOptics.jl`, the optical properties of bulk media (such as glass lenses, crystals, gases, or absorbing filters) are modeled through the [`RefractiveIndex`](@ref) interface. Bulk media support both **real** (lossless) and **complex** (absorbing or amplifying) refractive indices. + +--- + +## Complex Refractive Index & Physical Conventions + +A bulk medium is characterized by its complex refractive index: + +```math +\tilde{n}(\lambda) = n(\lambda) + i \kappa(\lambda) +``` + +where: +* ``n(\lambda) = \text{Re}(\tilde{n})`` is the **real refractive index**, governing phase velocity and Snellius refraction. +* ``\kappa(\lambda) = \text{Im}(\tilde{n})`` is the **extinction coefficient**, governing attenuation or amplification. + +### Sign Conventions + +`BeamletOptics.jl` follows standard optical conventions (where plane waves propagate as ``e^{i(kz - \omega t)}``): + +* **Bulk Absorption (``\kappa > 0``):** + The linear power absorption coefficient ``\alpha(\lambda)`` in $[1/\text{m}]$ (Lambert-Beer law) is given by: + ```math + \alpha(\lambda) = \frac{4\pi \kappa(\lambda)}{\lambda} + ``` + * **Power Attenuation ([`Ray`](@ref)):** + ```math + w(L) = w_0 \cdot e^{-\alpha L} = w_0 \cdot e^{-\frac{4\pi \kappa}{\lambda} L} + ``` + * **Field Amplitude Attenuation ([`PolarizedRay`](@ref), [`GaussianBeamlet`](@ref), [`AstigmaticGaussianBeamlet`](@ref)):** + ```math + E(L) = E_0 \cdot e^{-\frac{\alpha}{2} L} = E_0 \cdot e^{-\frac{2\pi \kappa}{\lambda} L} + ``` + +* **Small-Signal Gain (``\kappa < 0``):** + For active laser media with small-signal power gain coefficient ``g(\lambda)`` in $[1/\text{m}]$: + ```math + g(\lambda) = -\alpha(\lambda) = -\frac{4\pi \kappa(\lambda)}{\lambda} + ``` + * **Power Amplification:** ``w(L) = w_0 \cdot e^{+g L}`` + * **Field Amplification:** ``E(L) = E_0 \cdot e^{+\frac{g}{2} L}`` + +* **Snell's Law & Total Internal Reflection (TIR):** + Geometrical ray bending and critical angle evaluation use the real part ``\text{Re}(\tilde{n}) = n``. +* **Optical Path Length (OPL):** + The optical path length is computed as ``\text{OPL} = \int \text{Re}(\tilde{n}) \, \mathrm{d}s``, ensuring real-valued geometric path lengths. + +--- + +## Refractive Index Types & Wrappers + +Any callable object `f(λ::Real) -> Number` (returning a `Real` or `Complex` scalar) satisfies the [`RefractiveIndex`](@ref) interface. `BeamletOptics.jl` provides several built-in types: + +```@docs; canonical=false +BeamletOptics.RefractiveIndex +``` + +### AbsorbingMedium + +Use [`AbsorbingMedium`](@ref) to wrap a real base index with a known linear absorption coefficient $\alpha$ (in $[1/\text{m}]$): + +```@docs; canonical=false +AbsorbingMedium +``` + +#### Example: Absorbing Neutral Density Filter / Lens +```julia +using BeamletOptics + +# Absorbing medium with base index 1.5 and α = 100 1/m (1 1/cm) +med_abs = AbsorbingMedium(1.5, 100.0) + +# Can also use dispersion functions: +med_disp = AbsorbingMedium( + λ -> 1.51 + 0.005e-12 / λ^2, # n(λ) + λ -> 50.0 + 10.0e-6 / λ # α(λ) in 1/m +) + +# Create a 10 mm thick plano-planar absorbing block +slab = SphericalLens(Inf, Inf, 10e-3, 25.4e-3, med_abs) +``` + +### GainMedium + +Use [`GainMedium`](@ref) to model active laser gain materials with small-signal gain coefficient $g$ (in $[1/\text{m}]$): + +```@docs; canonical=false +GainMedium +``` + +#### Example: Nd:YAG Laser Crystal +```julia +using BeamletOptics + +# Nd:YAG crystal with n = 1.82 and small-signal gain g = 50 1/m at 1064 nm +yag_gain = GainMedium(1.82, 50.0) + +# 20 mm long AR-coated crystal +crystal = SphericalLens(Inf, Inf, 20e-3, 10e-3, yag_gain) |> with_coatings( + front = SimpleARCoating(0.0), + back = SimpleARCoating(0.0) +) +``` + +### Sellmeier Dispersion + +For transparent optical glasses specified by 6 Sellmeier coefficients: + +```@docs; canonical=false +SellmeierEquation +``` + +### Tabulated / Interpolated Indices + +For discrete tabulated refractive index data: + +```@docs; canonical=false +DiscreteRefractiveIndex +``` + +### Direct Anonymous Functions + +You can also directly pass anonymous functions returning complex numbers: + +```julia +# Direct complex refractive index: n + i*κ +n_direct = λ -> complex(1.60, 5e-4) +lens = SphericalLens(50e-3, -50e-3, 5e-3, 25.4e-3, n_direct) +``` + +--- + +## Helper Functions + +`BeamletOptics.jl` provides helper functions to query optical constants and compute attenuation factors: + +```@docs; canonical=false +real_refractive_index +extinction_coefficient +absorption_coefficient +bulk_attenuation_factor +``` + +--- + +## Interaction with Optical Coatings + +Bulk absorption and surface coatings operate independently and compose physically: +* **Bulk propagation:** Rays and beamlets attenuate as they travel through the medium according to $e^{-\alpha L}$. +* **Boundary physics:** When reaching a coated interface (e.g. [`ThinFilmCoating`](@ref) or [`SimpleARCoating`](@ref)), Fresnel reflection and transmission are evaluated at the boundary. diff --git a/docs/src/basics/components/mirrors.md b/docs/src/basics/components/mirrors.md index e429fc308..2b39b24dd 100644 --- a/docs/src/basics/components/mirrors.md +++ b/docs/src/basics/components/mirrors.md @@ -13,6 +13,10 @@ A common optical element with a straight-forward optical interaction. This kind Mirror ``` +!!! tip "Coated Mirrors" + To model mirrors with customized reflecting behaviors (such as specific power reflectance $R$ or thin-film multilayer coatings), see the [Coatings](@ref) section. You can construct a coated mirror using the fluent API `mirror |> with_coatings(front = SimpleHRCoating(0.999))`. + + The following constructors can be used to generate flat reflecting shapes. Additional types are explained below. - [`SquarePlanoMirror2D`](@ref) diff --git a/docs/src/basics/components/polarizers.md b/docs/src/basics/components/polarizers.md index 290e18363..b47d4390b 100644 --- a/docs/src/basics/components/polarizers.md +++ b/docs/src/basics/components/polarizers.md @@ -5,11 +5,7 @@ Polarizers in the context of this package are optical elements that select or mo 1. 3D polarization ray-tracing calculus 2. 3D modified Jones matrix calculus -For more information on the first method refer to the section: [Polarized rays](@ref). For the second approach, elements fall under the category of the [`BeamletOptics.AbstractJonesPolarizer`](@ref). - -```@docs; canonical=false -BeamletOptics.AbstractJonesPolarizer -``` +For more information on the first method refer to the section: [Polarized rays](@ref). For the second approach, elements use a [`Coating`](@ref) wrapping a [`JonesCoating`](@ref) model. ## Jones matrix element representation @@ -43,4 +39,39 @@ A polarisation filter or linear polarizer is the simplest practical polarizer an ```@docs; canonical=false PolarizationFilter(::Real) +``` + +--- + +## Waveplates + +Waveplates (or retarders) introduce a phase shift $\Gamma$ between two orthogonal polarization components. The fast axis is aligned along the local $x$-axis and the slow axis along the local $z$-axis (with propagation along the local $y$-axis), resulting in the local retardance matrix: + +```math +J_{\text{retarder}} = +\begin{pmatrix} +e^{-i\Gamma/2} & 0 & 0 \\ +0 & 1 & 0 \\ +0 & 0 & e^{i\Gamma/2} +\end{pmatrix} \,. +``` + +This package supports both **flat** (zero-thickness) and **thick/plate** waveplates (which include a bulk glass substrate of finite thickness $d$ and index $n$). The constructors automatically distinguish between **round** shapes (by passing a single `diameter` value) and **rectangular** shapes (by passing separate `width` and `height` values). + +```@docs; canonical=false +Waveplate +HalfWavePlate +QuarterWavePlate +RectangularPlateWaveplate +RoundPlateWaveplate +``` + +--- + +## Polarizing Cube Beamsplitter + +A Polarizing Cube Beamsplitter (PBS) consists of two joined right-angle prisms, separating the s- and p-polarization components of light at the hypotenuse interface: s-polarized light is completely reflected at 90°, while p-polarized light is completely transmitted. + +```@docs; canonical=false +PolarizingCubeBeamsplitter ``` \ No newline at end of file diff --git a/docs/src/basics/rays.md b/docs/src/basics/rays.md index 90a787cc5..40e77e7c3 100644 --- a/docs/src/basics/rays.md +++ b/docs/src/basics/rays.md @@ -37,7 +37,7 @@ PolarizedRay ### Fresnel coefficients -This package uses the equations of Fowles [Fowles1989; p. 44](@cite) and Peatross [Peatross2015; p. 78](@cite) to determine the [Fresnel coefficents](https://www.rp-photonics.com/fresnel_equations.html) at a given surface where the [`PolarizedRay`](@ref) enters from a medium with (complex) refractive index ``n_1`` into a medium with ``n_2``. The ability to define coatings is currently not included. +This package uses the equations of Fowles [Fowles1989; p. 44](@cite) and Peatross [Peatross2015; p. 78](@cite) to determine the [Fresnel coefficents](https://www.rp-photonics.com/fresnel_equations.html) at a given surface where the [`PolarizedRay`](@ref) enters from a medium with (complex) refractive index ``n_1`` into a medium with ``n_2``. Physical coatings can be attached to interfaces to modify these coefficients (supporting custom phase shifts, polarization-selective behaviors, and multi-layer thin films); see the [Coatings](@ref) section for details. !!! warning When a [`PolarizedRay`](@ref) interacts with a refractive medium, e.g. an [`BeamletOptics.AbstractRefractiveOptic`](@ref), the default tracing behaviour is to only trace the refracted and ignore the reflected ray, unless [Total Internal Reflection (TIR)](https://www.rp-photonics.com/total_internal_reflection.html) occurs. @@ -77,4 +77,14 @@ n2 = 1.0 rs, rp, ts, tp = BeamletOptics.fresnel_coefficients(θ, n2/n1) ``` -![Glass to vacuum](glass_to_vac.png) \ No newline at end of file +![Glass to vacuum](glass_to_vac.png) + +## Bulk Attenuation & Complex Media + +In addition to interface interactions, rays and beamlets propagating through absorbing or amplifying media experience bulk attenuation or small-signal gain according to their complex refractive index $\tilde{n} = n + i\kappa$: + +* **Power attenuation (`Ray`):** ``w(L) = w_0 e^{-\alpha L} = w_0 e^{-\frac{4\pi \kappa}{\lambda} L}`` +* **Electric field attenuation (`PolarizedRay`, `GaussianBeamlet`, `AstigmaticGaussianBeamlet`):** ``E(L) = E_0 e^{-\frac{\alpha}{2} L} = E_0 e^{-\frac{2\pi \kappa}{\lambda} L}`` +* **Small-signal gain:** for gain media ($\kappa < 0$), ``g = -\alpha > 0`` amplifies light as ``e^{+g L}``. + +For detailed information on defining absorbing materials and gain media, refer to the [Materials, Absorption & Gain](@ref) section. \ No newline at end of file diff --git a/docs/src/examples/coatings.md b/docs/src/examples/coatings.md new file mode 100644 index 000000000..26f5933c0 --- /dev/null +++ b/docs/src/examples/coatings.md @@ -0,0 +1,182 @@ +# Optical Coatings Examples + +This page provides practical examples demonstrating how to use coatings in `BeamletOptics.jl`. + +--- + +## Quarter-Wave Anti-Reflective Coating + +A standard method to minimize reflection at a dielectric boundary is a single quarter-wave thin-film layer. For normal incidence, the optimal refractive index of the coating layer $n_c$ between medium $n_1$ and $n_2$ is: + +```math +n_c = \sqrt{n_1 n_2} +``` + +The optimal physical thickness $d$ of the layer is: + +```math +d = \frac{\lambda_0}{4 n_c} +``` + +where $\lambda_0$ is the design wavelength. + +The following example compares the transmission of a single ray through an uncoated lens versus an AR-coated lens: + +```@example coatings_showcase +using BeamletOptics +const BMO = BeamletOptics + +# Setup parameters +λ = 1000e-9 # 1000 nm design wavelength +n_air = 1.0 +n_glass = 1.5 # substrate index + +# Calculate optimal AR coating properties +n_c = sqrt(n_air * n_glass) # ≈ 1.2247 +d_c = λ / (4 * n_c) # ≈ 204 nm + +# Define the coating model +ar_coating = ThinFilmCoating(n_c, d_c) + +# Create uncoated and coated plano-planar lenses +glass_index = λ -> n_glass +lens_uncoated = SphericalLens(Inf, Inf, 5e-3, 10e-3, glass_index) +lens_coated = lens_uncoated |> with_coatings(front = ar_coating) + +# Trace a polarized ray through both systems +ray_in_uncoated = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) +ray_in_coated = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) + +sys_uncoated = System([lens_uncoated]) +beam_uncoated = Beam(ray_in_uncoated) +solve_system!(sys_uncoated, beam_uncoated; retrace = false) + +sys_coated = System([lens_coated]) +beam_coated = Beam(ray_in_coated) +solve_system!(sys_coated, beam_coated; retrace = false) + +# Compare transmission at the front surface (Ray 2 is inside the lens) +ray_inside_uncoated = rays(beam_uncoated)[2] +ray_inside_coated = rays(beam_coated)[2] + +# Uncoated amplitude transmission: 2 * n1 / (n1 + n2) = 2 * 1 / (1 + 1.5) = 0.8 +println("Uncoated inside field amplitude: ", abs(BMO.polarization(ray_inside_uncoated)[1])) + +# Coated amplitude transmission: 100% power transmission -> amplitude factor is sqrt(n1 / n2) ≈ 0.8165 +println("AR-coated inside field amplitude: ", abs(BMO.polarization(ray_inside_coated)[1])) +``` + +--- + +## Polarizing Cube Beamsplitter + +Prism cube beamsplitters use a split-behavior coating on the hypotenuse interface of two cemented right-angle prisms. Here, we model a 50:50 splitter: + +```@example coatings_showcase +# Define leg length and substrate index +leg_length = 10e-3 +glass_idx = DiscreteRefractiveIndex([λ], [1.5]) + +# Construct a CubeBeamsplitter with 50% reflectance +cube_splitter = CubeBeamsplitter(leg_length, glass_idx; reflectance = 0.5) + +# Trace an Astigmatic Gaussian Beamlet at normal incidence to the front face +agb = AstigmaticGaussianBeamlet( + [0.0, -15e-3, 0.0], [0.0, 1.0, 0.0], λ, 1e-3; + E0 = [1.0, 0.0, 0.0], support = [0.0, 0.0, 1.0] +) + +system_bs = System([cube_splitter]) +solve_system!(system_bs, agb; retrace = false) + +# The beamsplitter splits the beamlet into a transmitted and reflected child +println("Number of split child beams: ", length(agb.children)) + +t_beam = agb.children[1] +r_beam = agb.children[2] + +# Show resulting intensities/amplitudes +using LinearAlgebra +println("Transmitted beam field amplitude: ", norm(BMO.electric_field(t_beam))) +println("Reflected beam field amplitude: ", norm(BMO.electric_field(r_beam))) +``` + +--- + +## Multi-layer Dielectric bandpass Filter + +Multi-layer thin-film coatings are used to make highly wavelength-selective optical filters (such as bandpass filters). This is done by stacking alternating layers of high-index (e.g. $TiO_2$, $n_H = 2.4$) and low-index (e.g. $SiO_2$, $n_L = 1.45$) materials. + +The following example designs a multi-layer stack of 9 alternating quarter-wave layers centered at $\lambda_0 = 800~\text{nm}$ and plots its reflectance spectrum: + +```@example coatings_showcase +using CairoMakie + +# Design parameters +λ0 = 800e-9 +nH = 2.4 +nL = 1.45 + +# Stacking alternating H and L layers +# HLHLHLHLH +ns = [nH, nL, nH, nL, nH, nL, nH, nL, nH] +ds = [λ0 / (4 * n) for n in ns] + +# Construct the thin-film coating model +filter_coating = ThinFilmCoating(ns, ds; behavior = Reflective()) + +# Evaluate reflectance over a spectrum range +wavelengths = range(400e-9, 1200e-9, length=200) +reflectances = Float64[] + +for wl in wavelengths + rs, rp, ts, tp = fresnel_coefficients(filter_coating, 0.0, wl, 1.0, 1.5) + push!(reflectances, abs(rs)^2) +end + +# Plot the spectrum +fig = Figure(size=(600, 350)) +ax = Axis(fig[1, 1], xlabel="Wavelength (nm)", ylabel="Reflectance", title="9-Layer Dielectric Filter Spectrum") +lines!(ax, wavelengths .* 1e9, reflectances, linewidth=2, color=:dodgerblue) +save("dielectric_filter_spectrum.png", fig); nothing # hide +``` + +![Dielectric filter spectrum](dielectric_filter_spectrum.png) + +--- + +## Frustrated Total Internal Reflection (FTIR) / Optical Tunneling + +When a ray strikes a glass-air boundary at an angle of incidence $\theta_i$ greater than the critical angle $\theta_c = \arcsin(1/n_{\text{glass}})$, total internal reflection (TIR) occurs. However, if a second glass block is placed extremely close to the first (within a fraction of a wavelength), the evanescent wave in the air gap is "frustrated". Light waves tunnel through the thin barrier, transmitting power into the second glass block. + +We can model the thin air gap as a `ThinFilmCoating` with a splitting behavior. Below, we calculate and plot the transmission coefficient $T_s = |t_s|^2$ as a function of the air gap thickness $d$: + +```@example coatings_showcase +# Setup physical parameters +λ = 632.8e-9 # 632.8 nm (He-Ne laser) +n_glass = 1.5 +n_gap = 1.0 # Air gap +θi = deg2rad(45.0) # 45° angle (> critical angle of ≈ 41.8°) + +# Evaluate transmission over a range of gap thicknesses +gap_thicknesses = range(0.0, 800e-9, length=200) +transmissions = Float64[] + +for d in gap_thicknesses + # Model the air gap of thickness d + gap_coating = ThinFilmCoating([n_gap], [d]; behavior = Splitting()) + rs, rp, ts, tp = fresnel_coefficients(gap_coating, θi, λ, n_glass, n_glass) + + # Power transmission transmissivity is |ts|^2 (since indices are matched) + push!(transmissions, abs(ts)^2) +end + +# Plot transmission vs air gap thickness +fig2 = Figure(size=(600, 350)) +ax2 = Axis(fig2[1, 1], xlabel="Air Gap Thickness (nm)", ylabel="Power Transmission (T)", title="Frustrated Total Internal Reflection (Optical Tunneling)") +lines!(ax2, gap_thicknesses .* 1e9, transmissions, linewidth=2, color=:crimson) +save("ftir_transmission_curve.png", fig2); nothing # hide +``` + +![Frustrated Total Internal Reflection](ftir_transmission_curve.png) + diff --git a/docs/src/examples/polarizing_optics.md b/docs/src/examples/polarizing_optics.md new file mode 100644 index 000000000..1aa865260 --- /dev/null +++ b/docs/src/examples/polarizing_optics.md @@ -0,0 +1,109 @@ +# Polarizing Optics Examples + +This page provides practical examples demonstrating how to use waveplates (Half-Wave Plates and Quarter-Wave Plates) and Polarizing Cube Beamsplitters in `BeamletOptics.jl` to manipulate and route polarized light. + +--- + +## Circular Polarization Generation (Quarter-Wave Plate) + +A Quarter-Wave Plate (QWP) introduces a relative phase retardance of $\pi/2$ (a quarter-wavelength) between the fast and slow axes of the waveplate. When linearly polarized light passes through a QWP at an angle of 45° relative to the fast axis, the output light becomes circularly polarized. + +The following example demonstrates how to set up a flat, circular QWP to generate circularly polarized light: + +```@example polarizing_showcase +using BeamletOptics +using LinearAlgebra +const BMO = BeamletOptics + +# Define QWP (diameter = 10 mm, retardance = π/2) with fast axis at 0° (along x-axis) +qwp = QuarterWavePlate(10e-3; fast_axis_angle = 0.0) +system = System([qwp]) + +# Input beam linearly polarized at 45° in the transverse plane (x-z plane) +# propagation along y-axis +ray_in = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9, [1.0, 0.0, 1.0] / sqrt(2)) +beam = Beam(ray_in) + +# Trace ray through system +solve_system!(system, beam; retrace = false) + +# Analyze exit polarization +ray_out = rays(beam)[2] +E_out = BMO.polarization(ray_out) + +println("Input polarization: ", BMO.polarization(ray_in)) +println("Output polarization: ", E_out) +println("Magnitude X-component: ", abs(E_out[1])) +println("Magnitude Z-component: ", abs(E_out[3])) +``` + +As shown above, the $x$- and $z$-components of the output electric field have equal magnitude ($\approx 0.707$) and a phase difference of 90° ($e^{i \pi/2} = i$), which corresponds to circularly polarized light. + +--- + +## Linear Polarization Rotation (Half-Wave Plate) + +A Half-Wave Plate (HWP) introduces a relative phase retardance of $\pi$ (a half-wavelength) between the fast and slow axes. If linearly polarized light is incident on a HWP with its polarization plane at an angle $\theta$ relative to the fast axis, the plane of polarization is rotated by $2\theta$. + +In this example, we rotate horizontal linear polarization ([1, 0, 0]) by 45° by setting the HWP's fast axis at 22.5°: + +```@example polarizing_showcase +# Create flat HWP with fast axis oriented at 22.5° (0.3927 radians) +hwp = HalfWavePlate(10e-3; fast_axis_angle = deg2rad(22.5)) +system_hwp = System([hwp]) + +# Input horizontal polarization along x-axis +ray_in_hwp = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9, [1.0, 0.0, 0.0]) +beam_hwp = Beam(ray_in_hwp) + +# Trace ray through system +solve_system!(system_hwp, beam_hwp; retrace = false) + +# Output polarization +ray_out_hwp = rays(beam_hwp)[2] +E_out_hwp = BMO.polarization(ray_out_hwp) + +println("Input polarization: ", BMO.polarization(ray_in_hwp)) +println("Output polarization: ", E_out_hwp) +``` + +The output polarization vector is approximately `[0.0 - 0.707im, 0.0, 0.0 - 0.707im]`, which corresponds to a linear polarization state oriented at 45° in the transverse plane with an overall global phase shift of -90° (represented by the common factor of `-im`). + +--- + +## Polarization Routing (Polarizing Beamsplitter Cube) + +A Polarizing Beamsplitter Cube (PBS) splits an incoming beam into two polarized components. Light polarized perpendicular to the plane of incidence (s-polarization) is reflected at a 90° angle, while light polarized parallel to the plane of incidence (p-polarization) is transmitted straight through the cube. + +This example splits an input beam containing equal s- and p-components: + +```@example polarizing_showcase +# Define PBS with leg length 25 mm and refractive index n = 1.5 +pbs = PolarizingCubeBeamsplitter(25e-3, n -> 1.5) +# Shift it forward so the center lies at y = 50 mm +translate3d!(pbs, [0.0, 50e-3, 0.0]) +system_pbs = System([pbs]) + +# Input beam with equal s- and p-polarized components (linear at 45°) +ray_in_pbs = PolarizedRay([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], 1000e-9, [1.0, 0.0, 1.0] / sqrt(2)) +beam_pbs = Beam(ray_in_pbs) + +# Trace the beam (depth_max = 2 to allow multiple reflections/refractions through the cube boundaries) +solve_system!(system_pbs, beam_pbs; depth_max = 2, retrace = false) + +# Examine child beams +# children[1] is the transmitted beam +# children[2] is the reflected beam +transmitted = beam_pbs.children[1] +reflected = beam_pbs.children[2] + +println("Number of child beams: ", length(beam_pbs.children)) +println("Transmitted beam direction: ", direction(last(rays(transmitted)))) +println("Transmitted polarization: ", BMO.polarization(last(rays(transmitted)))) +println("Reflected beam direction: ", direction(last(rays(reflected)))) +println("Reflected polarization: ", BMO.polarization(last(rays(reflected)))) +``` + +As demonstrated: +* The transmitted beam propagates straight along `[0, 1, 0]` and contains the p-polarized component scaled to $\approx [0.679, 0.0, 0.0]$ due to Fresnel reflection losses at the entrance and exit surfaces of the glass cube. +* The reflected beam is redirected by 90° along `[-1, 0, 0]` and contains the s-polarized component $\approx [0.0, 0.0, -0.679]$ (where the negative sign arises from local coordinate conventions). diff --git a/docs/src/refs.bib b/docs/src/refs.bib index 7c2f8fc2c..652c4b49b 100644 --- a/docs/src/refs.bib +++ b/docs/src/refs.bib @@ -359,4 +359,18 @@ @article{KochkinaAO:2013 year = {2013}, url = {https://opg.optica.org/ao/abstract.cfm?URI=ao-52-24-6030}, doi = {10.1364/AO.52.006030}, +} + +@article{Ewers:2019, + author = {Benjamin Ewers and Raoul-Amadeus Lorbeer}, + journal = {OSA Continuum}, + number = {5}, + pages = {1502--1509}, + publisher = {Optica Publishing Group}, + title = {Interference filter based beam confinement for increased mechanical phase modulation}, + volume = {2}, + month = {May}, + year = {2019}, + url = {https://opg.optica.org/osac/fulltext.cfm?uri=osac-2-5-1502}, + doi = {10.1364/OSAC.2.001502}, } \ No newline at end of file diff --git a/docs/src/tutorials/fabry_perot.md b/docs/src/tutorials/fabry_perot.md new file mode 100644 index 000000000..ffb23f640 --- /dev/null +++ b/docs/src/tutorials/fabry_perot.md @@ -0,0 +1,158 @@ +# Fabry-Pérot Cavity Resonator + +This tutorial demonstrates how to simulate a Fabry-Pérot cavity resonator and model coherent multiple-reflection interference using the ray-splitting features of `BeamletOptics.jl`. + +We will explore: +- Setting up a parallel-mirror Fabry-Pérot etalon. +- Tracing an `AstigmaticGaussianBeamlet` with active ray-splitting. +- Pruning infinite round trips using the `power_cutoff` option. +- Simulating the wavelength transmission spectrum (Airy distribution). +- Introducing a small wedge to observe spatial interference fringes (Fizeau-like fringes). + +--- + +## Cavity Resonator Concept + +A Fabry-Pérot resonator consists of a transparent plate (etalon) or cavity bounded by two parallel, partially reflective surfaces. + +When a light beam is incident on the cavity: +- A portion of the light enters the cavity through the front face. +- Inside the cavity, the light undergoes multiple internal reflections between the front and back surfaces. +- At each bounce, a fraction of the light transmits through the back face. +- These multiple transmitted beams exit parallel to each other and interfere coherently. + +If the round-trip path length is an integer multiple of the laser wavelength, the transmitted beams interfere constructively, resulting in maximum transmission (resonance). Otherwise, they interfere destructively, causing high reflectance. + +--- + +## Parallel Mirror Resonance Scan + +First, we set up a parallel-mirror cavity (etalon) using a flat glass substrate (modelled as a plano-planar `SphericalLens` with infinite radii of curvature) coated on both sides with a beam-splitting coating. + +```@example fabry_perot +using BeamletOptics +using LinearAlgebra +using CairoMakie + + +const mm = 1e-3 +const μm = 1e-6 + +# Define cavity parameters +d = 10.0μm # Center spacing +n_glass = 1.5 # Refractive index of substrate +R_power = 0.8 # Power reflectance (80%) +T_power = 1.0 - R_power + +r = sqrt(R_power) +t = sqrt(T_power) + +# Define a beam-splitting coating +splitting_coating = SimpleBeamsplitterCoating(r, r, t, t) + +# Construct flat glass etalon (SphericalLens of thickness d) +etalon_base = SphericalLens(Inf, Inf, d, 2.0mm, λ -> n_glass) +etalon = etalon_base |> with_coatings(front = splitting_coating, back = splitting_coating) + +# Place a photodetector behind the etalon +pd = Detector(1.0mm) +translate3d!(pd, [0.0, 1.0mm, 0.0]) + +# Assemble the system +system = System([etalon, pd]) +nothing # hide +``` + +Since the reflections continue infinitely, a simple ray trace would lead to infinite branching. To keep the simulation finite, we use the `power_cutoff = 1e-4` argument in `solve_system!`. Once the power weight of a split ray path falls below $0.01\%$, tracing on that branch is stopped and the sub-branch is dropped. + +We will scan the wavelength of the incident astigmatic Gaussian beamlet from 620 nm to 630 nm to observe the Airy resonance peak. + +```@example fabry_perot +lambdas = LinRange(620e-9, 630e-9, 101) +powers = Float64[] + +for λ in lambdas + empty!(pd) + # Start AstigmaticGaussianBeamlet propagating along +y with explicit initial power P0 = 1.0 W + beam = AstigmaticGaussianBeamlet([0.0, -1.0mm, 0.0], [0.0, 1.0, 0.0], λ, 100.0μm, P0 = 1.0) + solve_system!(system, beam; power_cutoff = 1e-4, retrace = false) + push!(powers, optical_power(pd; n=20)) +end + +# Find resonance peaks +fig_airy = Figure(size = (600, 350)) +ax_airy = Axis(fig_airy[1, 1], xlabel = "Wavelength [nm]", ylabel = "Transmitted Power [W]", title = "Airy Resonance Spectrum") +lines!(ax_airy, lambdas ./ 1e-9, powers, color = :red, linewidth = 2) +vlines!(ax_airy, 625.0, color = :blue, linestyle = :dash) # Theoretical resonance peak (m = 48) + +save("fabry_perot_airy.png", fig_airy) # hide +nothing # hide +``` + +![Airy Resonance Peak](fabry_perot_airy.png) + +At $\lambda = 625$ nm, the optical path length of a round trip inside the glass is $2 \cdot n \cdot d = 2 \cdot 1.5 \cdot 10\,\mu\text{m} = 30\,\mu\text{m}$, which is exactly $48$ times the wavelength. Thus, the multiple internal reflections interfere constructively, producing a sharp transmission peak of over $90\%$ of the initial laser power. + +--- + +## Wedged Cavity and Spatial Fizeau Fringes + +Next, we introduce a slight wedge to the cavity. Instead of parallel mirrors, we tilt the mirrors relative to each other by $0.1^\circ$. This creates a spatially varying cavity thickness along the x-direction: +$$d(x) = d_0 + x \cdot \tan\alpha$$ + +This thickness variation translates to a spatially varying phase shift across the profile of the beam, producing spatial interference fringes (Fizeau fringes) on the detector face. + +### Physical Astigmatism from Mirror Tilt + +Introducing a wedge angle means the beam's reflections off the cavity mirrors are no longer at normal incidence. Non-normal reflection off curved or flat boundaries introduces astigmatism to the wavefront (the tangential and sagittal curvatures propagate differently). + +To model this physical phenomenon accurately, we must use an `AstigmaticGaussianBeamlet` (AGB) rather than a circular `GaussianBeamlet`. The AGB dynamically updates its full 3D complex curvature matrix at each tilted surface crossing, capturing the realistic spatial profiles of the interfering beams. + +To build the wedged cavity, we construct the setup using two separate flat `SphericalLens` objects with coatings so we can orient them independently: + +```@example fabry_perot +# Wedge angle +α = deg2rad(0.1) + +# Mirror 1 (Entrance) - Flat CoatedLens tilted by +α/2 +m1_base = SphericalLens(Inf, Inf, 0.5mm, 5.0mm, λ -> n_glass) +mirror1 = m1_base |> with_coatings(back = splitting_coating, front = SimpleARCoating(0.0)) +translate3d!(mirror1, [0.0, -0.25mm, 0.0]) # Front face near y = -0.5mm, back face at y = 0 +zrotate3d!(mirror1, α/2) + +# Mirror 2 (Exit) - Flat CoatedLens tilted by -α/2 +m2_base = SphericalLens(Inf, Inf, 0.5mm, 5.0mm, λ -> n_glass) +mirror2 = m2_base |> with_coatings(front = splitting_coating, back = SimpleARCoating(0.0)) +translate3d!(mirror2, [0.0, 20.0μm + 0.25mm, 0.0]) # Front face at y = 20μm +zrotate3d!(mirror2, -α/2) + +# Photodetector placed behind the cavity +pd_wedge = Detector(1.5mm) +translate3d!(pd_wedge, [0.0, 2.0mm, 0.0]) + +# Assemble the wedged system +system_wedge = System([mirror1, mirror2, pd_wedge]) +``` + +Now, we launch a wide astigmatic Gaussian beamlet ($\lambda = 632.8$ nm, waist $w_0 = 300\,\mu$m, explicitly setting initial power $P_0 = 1.0$ W) and capture the high-resolution 2D spatial intensity map on the detector. + +```@example fabry_perot +# Start beam and solve the system +beam_wedge = AstigmaticGaussianBeamlet([0.0, -1.0mm, 0.0], [0.0, 1.0, 0.0], 632.8e-9, 300.0μm, P0 = 1.0) +solve_system!(system_wedge, beam_wedge; power_cutoff = 1e-4, retrace = false) + +# Compute high-resolution 2D intensity grid +x_grid, z_grid, I_map = intensity(pd_wedge, n=500) + +# Plot Fizeau fringes +fig_fizeau = Figure(size = (600, 500)) +ax_fizeau = Axis(fig_fizeau[1, 1], xlabel = "x [mm]", ylabel = "z [mm]", title = "Fizeau Spatial Interference Fringes", aspect = 1) +heatmap!(ax_fizeau, x_grid ./ mm, z_grid ./ mm, I_map, colormap = :viridis) + +save("fabry_perot_fizeau.png", fig_fizeau) # hide +nothing # hide +``` + +![Fizeau Fringes](fabry_perot_fizeau.png) + +The heatmap displays parallel vertical fringes, demonstrating how the phase differences vary linearly across the beam profile due to the wedge geometry. The fringe spacing matches the analytical expectation $\Delta x = \lambda / (2 \cdot \tan\alpha) \approx 0.18$ mm perfectly. diff --git a/docs/src/tutorials/wolit_trap.md b/docs/src/tutorials/wolit_trap.md new file mode 100644 index 000000000..95ad0d2f6 --- /dev/null +++ b/docs/src/tutorials/wolit_trap.md @@ -0,0 +1,160 @@ +# Wedge interference filter light trap (WOLIT) + +This example demonstrates how to implement a custom angle-dependent thin film interference filter coating and simulate a He-Ne laser wedge light trap (Wedge Optical Light Trap / WOLIT) as described by Ewers & Lorbeer (2019) [Ewers:2019](@cite). + +--- + +## Wedge Light Trap Concept + +A wedge light trap consists of two surfaces set at a small angle relative to each other (a wedge): +* The top surface is a highly-reflective (HR) mirror. +* The bottom surface is coated with a custom bandpass or edge filter. + +The edge filter's cut-off wavelength shifts with the angle of incidence (AOI) according to the formula: + +```math +\lambda_{\text{edge}}(\theta) = \lambda_0 \sqrt{1 - \frac{\sin^2(\theta_{\text{air}})}{n_{\text{eff}}^2}} +``` + +where $\lambda_0$ is the cut-off wavelength at normal incidence, $\theta_{\text{air}}$ is the angle of incidence in air, and $n_{\text{eff}}$ is the effective refractive index of the filter cavity. + +A laser ray enters the wedge at a high angle of incidence where the filter is transmissive. As the ray bounces between the mirror and the filter, the wedge geometry reduces the angle of incidence with each bounce. Eventually, the angle of incidence falls below the critical threshold where the filter becomes highly reflective, trapping the ray. The ray travels towards the wedge apex, reverses direction, and travels back towards the entrance where the angle of incidence increases again until it exits the cavity. + +--- + +## Custom Coating Definition + +First, we define a custom coating type that wraps a transmissive model (AR coating) and a reflective model (HR coating), switching between them based on the angle-dependent cut-off wavelength. + +```@example wolit_trap +using BeamletOptics +using LinearAlgebra +using CairoMakie + + +const mm = 1e-3 + +# Custom Coating definition representing the WOLIT filter +struct WolitFilterCoating + lambda_0::Float64 + n_eff::Float64 + laser_lambda::Float64 + transmissive_model::SimpleARCoating + reflective_model::SimpleHRCoating +end + +# Constructor +function WolitFilterCoating(lambda_0, n_eff, laser_lambda) + return WolitFilterCoating( + lambda_0, n_eff, laser_lambda, + SimpleARCoating(0.02), + SimpleHRCoating(0.999) + ) +end + +# Overload coating_behavior dynamically based on the ray's angle of incidence +function BeamletOptics.coating_behavior(coating::WolitFilterCoating, ray) + int = BeamletOptics.intersection(ray) + normal = BeamletOptics.normal3d(int) + n_incident = BeamletOptics.refractive_index(ray) + cos_θ = abs(dot(BeamletOptics.direction(ray), normal)) + sin_θ = sqrt(max(0.0, 1.0 - cos_θ^2)) + sin_θ_air = n_incident * sin_θ + sin_θ_air = clamp(sin_θ_air, 0.0, 1.0) + λ_edge = coating.lambda_0 * sqrt(1.0 - sin_θ_air^2 / coating.n_eff^2) + + if coating.laser_lambda > λ_edge + return BeamletOptics.Transmissive() + else + return BeamletOptics.Reflective() + end +end + +# Overload get_jones_matrix +function BeamletOptics.get_jones_matrix(coating::WolitFilterCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true) + # The filter formula uses the angle of incidence in air + sin_θ_air = n1 * sin(θi) + sin_θ_air = clamp(sin_θ_air, 0.0, 1.0) + λ_edge = coating.lambda_0 * sqrt(1.0 - sin_θ_air^2 / coating.n_eff^2) + + if coating.laser_lambda > λ_edge + # Transmissive state + return BeamletOptics.get_jones_matrix(coating.transmissive_model, θi, λ, n1, n2, is_reflected; from_front = from_front) + else + # Reflective state + return BeamletOptics.get_jones_matrix(coating.reflective_model, θi, λ, n1, n2, is_reflected; from_front = from_front) + end +end +``` + +--- + +## Simulating the Wedge Cavity + +We assemble the optical system containing the flat top mirror and the bottom wedge mirror. We then trace a ray entering at an angle of 26.5 degrees. + +```@example wolit_trap +# Setup wavelength and coating properties +λ = 632.8e-9 # He-Ne laser wavelength (red light) +λ_cut = 650e-9 # Filter cut-off at normal incidence (650 nm) +n_eff = 1.85 # Effective refractive index of the filter cavity +α = deg2rad(1.2) # Wedge angle: 1.2 degrees +d = 1.0mm # Wedge thickness at origin (x=0) + +# Define custom WolitFilterCoating +wolit_coating = WolitFilterCoating(λ_cut, n_eff, λ) + +# Mirror 1: highly reflective mirror at y = 1.0mm, tilted by -α/2 +m1_base = RectangularPlanoMirror(15mm, 2mm, 0.25mm) +mirror1 = with_coatings(m1_base; front = SimpleHRCoating(0.999)) +translate3d!(mirror1, [0.0, d, 0.0]) +zrotate3d!(mirror1, -α/2) + +# Mirror 2: custom coated rectangular plano mirror substrate (filter) at y = 0 +# The bottom face is AR coated and the top face is the WolitFilterCoating +m2_base = RectangularPlanoMirror(15mm, 2mm, 0.25mm) +mirror2 = with_coatings(m2_base; front = SimpleARCoating(0.0), back = wolit_coating) +translate3d!(mirror2, [0.0, -0.25mm, 0.0]) +zrotate3d!(mirror2, α/2) + +# Assemble the system +system = System([mirror1, mirror2]) + +# Define and trace the incoming ray +θ_in = deg2rad(26.5) +pos_in = [-5.5mm, -2.5mm, 0.0] +dir_in = [sin(θ_in), cos(θ_in), 0.0] +pol_in = [0.0, 0.0, 1.0] # s-polarized, orthogonal to x-y plane + +ray_in = PolarizedRay(pos_in, dir_in, λ, pol_in) +beam = Beam(ray_in) + +# Trace the ray through the system +solve_system!(system, beam; r_max = 200, retrace = false) +all_rays = rays(beam) +n_rays = length(all_rays) +println("Total segments traced: $n_rays") +``` + +--- + +## 3D Visualization + +Using CairoMakie, we render the layout of the wedge trap and the path of the multi-bounce ray inside the cavity. + +```@example wolit_trap +fig = Figure(size = (800, 600)) +ax = LScene(fig[1, 1]) +ax.show_axis[] = false + +# Render the optical system and the traced beam +render!(ax, system) +render!(ax, beam, linewidth = 2.5, color = :red, flen=1mm) + +update_cam!(ax.scene, Vec3f(-2.2mm, -0.5mm, 4.8mm), Vec3f(-1.0mm, 0.5mm, 0.0), Vec3f(0.0, 0.0, 1.0)) # hide + +save("wolit_trap.png", fig) # hide +nothing # hide +``` + +![WOLIT Wedge Trap](wolit_trap.png) diff --git a/ext/BeamletOpticsMakieExt.jl b/ext/BeamletOpticsMakieExt.jl index 95945bc34..7f551c5f7 100644 --- a/ext/BeamletOpticsMakieExt.jl +++ b/ext/BeamletOpticsMakieExt.jl @@ -6,10 +6,11 @@ import BeamletOptics: render!, RenderException, _RenderTypes, get_view, set_view const BMO = BeamletOptics using Makie: Axis3, LScene, mesh!, surface!, lines!, RGBf, RGBAf, scatter! -using GeometryBasics: Point2, Point3 +using GeometryBasics: Point2, Point3, TriangleFace using AbstractTrees: PreOrderDFS using MarchingCubes: MC, march using LinearAlgebra: dot, cross, normalize +using StaticArrays: SVector const _RenderEnv = Union{ Axis3, diff --git a/ext/RenderObjects.jl b/ext/RenderObjects.jl index c961b7ba5..7840e7ab7 100644 --- a/ext/RenderObjects.jl +++ b/ext/RenderObjects.jl @@ -28,6 +28,42 @@ function render!(ax::_RenderEnv, ::BMO.SingleShape, obj; kwargs...) return nothing end +function render!(ax::_RenderEnv, ::BMO.SingleShape, lens::BMO.Lens; color = RGBf(0.678, 0.847, 0.902), kwargs...) + s = BMO.shape(lens) + if s isa BMO.UnionSDF && !isempty(BMO.coatings(lens)) + for sub_sdf in s.sdfs + if sub_sdf isa BMO.ConcaveSphericalSurfaceSDF || sub_sdf isa BMO.ConvexSphericalSurfaceSDF || sub_sdf isa BMO.AbstractAsphericalSurfaceSDF + sub_opt_axis = orientation(sub_sdf)[:, 2] + lens_opt_axis = orientation(lens)[:, 2] + local_n = if dot(sub_opt_axis, lens_opt_axis) < 0 + SVector{3, Float64}(0.0, -1.0, 0.0) # front surface + else + SVector{3, Float64}(0.0, 1.0, 0.0) # back surface + end + c_model = BMO.get_matching_coating(BMO.coatings(lens), s, [0.0, 0.0, 0.0], local_n) + sub_color = coating_color(c_model, color) + render!(ax, sub_sdf; color = sub_color, kwargs...) + else + render!(ax, sub_sdf; color = color, kwargs...) + end + end + else + render!(ax, s; color = color, kwargs...) + end + return nothing +end + +function render!(ax::_RenderEnv, ::BMO.SingleShape, mirror::BMO.Mirror; color = :silver, kwargs...) + if !isempty(BMO.coatings(mirror)) + c_model = BMO.get_matching_coating(BMO.coatings(mirror), BMO.shape(mirror), [0.0, 0.0, 0.0], [0.0, -1.0, 0.0]) + m_color = c_model isa BMO.Uncoated ? color : coating_color(c_model, color) + render!(ax, BMO.shape(mirror); color = m_color, kwargs...) + else + render!(ax, BMO.shape(mirror); color = color, kwargs...) + end + return nothing +end + function render!(ax::_RenderEnv, ::BMO.MultiShape, obj; kwargs...) for _obj in BMO.shape(obj) render!(ax, _obj; kwargs...) diff --git a/ext/RenderPresets.jl b/ext/RenderPresets.jl index 100712db5..3a5707b12 100644 --- a/ext/RenderPresets.jl +++ b/ext/RenderPresets.jl @@ -1,10 +1,19 @@ -render!(ax::_RenderEnv, refr::BMO.AbstractRefractiveOptic; kwargs...) = _render!(ax, refr; transparency=true, color=:white, kwargs...) +# Coating visualization palette +coating_color(::BMO.Uncoated, default_color = RGBAf(0.678, 0.847, 0.902, 0.4)) = default_color +coating_color(::BMO.SimpleARCoating, default_color = nothing) = RGBAf(0.18, 0.80, 0.44, 0.65) +coating_color(::BMO.SimpleHRCoating, default_color = nothing) = RGBAf(0.95, 0.77, 0.20, 0.95) +coating_color(::BMO.SimpleBeamsplitterCoating, default_color = nothing) = RGBAf(0.90, 0.49, 0.13, 0.70) +coating_color(::BMO.JonesCoating, default_color = nothing) = RGBAf(0.60, 0.20, 0.80, 0.70) +coating_color(::BMO.ThinFilmCoating, default_color = nothing) = RGBAf(0.10, 0.74, 0.61, 0.65) +coating_color(::BMO.AbstractCoatingModel, default_color = RGBAf(0.85, 0.45, 0.85, 0.70)) = default_color + +render!(ax::_RenderEnv, refr::BMO.AbstractRefractiveOptic; kwargs...) = _render!(ax, refr; transparency=true, color=RGBf(0.678, 0.847, 0.902), alpha=0.5, kwargs...) render!(ax::_RenderEnv, refl::BMO.AbstractReflectiveOptic; kwargs...) = _render!(ax, refl; transparency=false, color=:silver, kwargs...) render!(ax::_RenderEnv, lens::Lens; kwargs...) = _render!(ax, lens; transparency=true, color=RGBf(0.678, 0.847, 0.902), alpha=0.5, kwargs...) render!(ax::_RenderEnv, lens::DoubletLens; kwargs...) = _render!(ax, lens; transparency=true, color=RGBf(0.678, 0.847, 0.902), alpha=0.5, kwargs...) -render!(ax::_RenderEnv, bs::ThinBeamsplitter; kwargs...) = _render!(ax, bs; transparency=true, color=:magenta, kwargs...) +render!(ax::_RenderEnv, c::Coating; kwargs...) = _render!(ax, c; transparency=true, color=coating_color(c.model), kwargs...) render!(ax::_RenderEnv, nino::BMO.NonInteractableObject; kwargs...) = _render!(ax, nino; transparency=false, color=:grey, kwargs...) diff --git a/ext/RenderSDF.jl b/ext/RenderSDF.jl index 6f202937b..c68860231 100644 --- a/ext/RenderSDF.jl +++ b/ext/RenderSDF.jl @@ -23,9 +23,9 @@ function render!( sdf_values = Float32.([BMO.sdf(sdf, [i, j, k]) for i in x, j in y, k in z]) mc = MC(sdf_values; x = Float32.(x), y = Float32.(y), z = Float32.(z)) march(mc) - vertices = transpose(reinterpret(reshape, Float32, mc.vertices)) - faces = transpose(reinterpret(reshape, Int64, mc.triangles)) - mesh!(ax, vertices, faces; kwargs...) + pts = Point3{Float32}[Point3{Float32}(v...) for v in mc.vertices] + fcs = [TriangleFace{Int}(t...) for t in mc.triangles] + mesh!(ax, pts, fcs; kwargs...) return nothing end diff --git a/src/OpticalComponents/Beamsplitters/Beamsplitters.jl b/src/OpticalComponents/Beamsplitters/Beamsplitters.jl index be867d56f..56217e882 100644 --- a/src/OpticalComponents/Beamsplitters/Beamsplitters.jl +++ b/src/OpticalComponents/Beamsplitters/Beamsplitters.jl @@ -30,4 +30,6 @@ abstract type AbstractBeamsplitter{T} <: AbstractObject{T} end include("ThinBeamsplitter.jl") include("PlateBeamsplitter.jl") include("CubeBeamsplitter.jl") +include("PolarizingCubeBeamsplitter.jl") +include("PolarizingBeamSplitter.jl") include("Compensators.jl") \ No newline at end of file diff --git a/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl index 0bd81ba38..7c8cb6684 100644 --- a/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/CubeBeamsplitter.jl @@ -9,9 +9,8 @@ For more information refer to the [`AbstractPlateBeamsplitter`](@ref) docs. # Fields -- `front`: the forward facing substrate, represented by a [`RightAnglePrism`](@ref) +- `front`: the forward facing substrate, represented by a coated prism (coated [`RightAnglePrism`](@ref)) - `back`: the backward facing substrate, represented by a [`RightAnglePrism`](@ref) -- `coating`: a rectangular [`ThinBeamsplitter`](@ref) that represents the splitting interface # Additional information @@ -19,15 +18,16 @@ For more information refer to the [`AbstractPlateBeamsplitter`](@ref) docs. In order to model gap-free beam propagation, the `interact3d` model relies heavily on the [`Hint`](@ref)-API. If the `front` or `back` substrate is hit, the `Hint` will ensure that the beam intersects the `coating`. """ -struct CubeBeamsplitter{T} <: AbstractBeamsplitter{T} - front::Prism{T, RightAnglePrismSDF{T}} - back::Prism{T, RightAnglePrismSDF{T}} - coating::ThinBeamsplitter{T, Mesh{T}} +struct CubeBeamsplitter{T, F, B} <: AbstractObjectGroup{T} + front::F + back::B end shape_trait_of(::CubeBeamsplitter) = MultiShape() -shape(cbs::CubeBeamsplitter) = (cbs.front, cbs.back, cbs.coating) +shape(cbs::CubeBeamsplitter) = (cbs.front, cbs.back) + +objects(cbs::CubeBeamsplitter) = (cbs.front, cbs.back) refractive_index(cbs::CubeBeamsplitter, λ::Real) = refractive_index(cbs.front, λ) @@ -51,100 +51,17 @@ function CubeBeamsplitter( n::RefractiveIndex; reflectance::Real=0.5 ) - front = RightAnglePrism(leg_length, leg_length, n) - back = RightAnglePrism(leg_length, leg_length, n) - bs = ThinBeamsplitter(√2*leg_length, leg_length; reflectance) + T = float(typeof(leg_length)) + front_prism = RightAnglePrism(T(leg_length), T(leg_length), n) + back = RightAnglePrism(T(leg_length), T(leg_length), n) zrotate3d!(back, deg2rad(180)) - zrotate3d!(bs, deg2rad(180-45)) - set_new_origin3d!(shape(bs)) - return CubeBeamsplitter(front, back, bs) -end -function interact3d( - system::AbstractSystem, - cbs::CubeBeamsplitter, - beam::Beam{T, R}, - ray::R) where {T <: Real, R <: AbstractRay{T}} - # Front prism interaction - if shape(intersection(ray)) === shape(cbs.front) - interaction = interact3d(system, cbs.front, beam, ray) - # Hint towards coating - hint!(interaction, Hint(cbs, shape(cbs.coating))) - return interaction - end - # Splitter "coating" interaction - if shape(intersection(ray)) === shape(cbs.coating) - # Beamsplitter coating interaction - interact3d(system, cbs.coating, beam, ray) - # Update refractive index - _n = refractive_index(cbs, wavelength(ray)) - refractive_index!(first(rays(beam.children[1])), _n) - refractive_index!(first(rays(beam.children[2])), _n) - return nothing - end - # Back prism interaction - if shape(intersection(ray)) === shape(cbs.back) - interaction = interact3d(system, cbs.back, beam, ray) - # Hint towards coating - hint!(interaction, Hint(cbs, shape(cbs.coating))) - return interaction - end -end + coat_bs = SimpleBeamsplitterCoating( + sqrt(reflectance), sqrt(reflectance), + sqrt(1.0 - reflectance), sqrt(1.0 - reflectance) + ) -function interact3d( - system::AbstractSystem, - cbs::CubeBeamsplitter, - gauss::GaussianBeamlet, - id::Int) - _shape = shape(intersection(rays(gauss.chief)[id])) - # Front prism interaction - if _shape === shape(cbs.front) - interaction = interact3d(system, cbs.front, gauss, id) - hint!(interaction, Hint(cbs, shape(cbs.coating))) - return interaction - end - # Splitter "coating" interaction - if _shape === shape(cbs.coating) - interact3d(system, cbs.coating, gauss, id) - # Update refractive index - _n = refractive_index(cbs, wavelength(gauss)) - refractive_index!(gauss.children[1], 1, _n) - refractive_index!(gauss.children[2], 1, _n) - return nothing - end - # Back prism interaction - if _shape === shape(cbs.back) - interaction = interact3d(system, cbs.back, gauss, id) - hint!(interaction, Hint(cbs, shape(cbs.coating))) - return interaction - end -end + front = with_coatings(front_prism, :hypotenuse => coat_bs) -function interact3d( - system::AbstractSystem, - cbs::CubeBeamsplitter, - agb::AstigmaticGaussianBeamlet, - id::Int) - _shape = shape(intersection(rays(agb.c)[id])) - # Front prism interaction - if _shape === shape(cbs.front) - interaction = interact3d(system, cbs.front, agb, id) - hint!(interaction, Hint(cbs, shape(cbs.coating))) - return interaction - end - # Splitter "coating" interaction - if _shape === shape(cbs.coating) - interact3d(system, cbs.coating, agb, id) - # Update refractive index - _n = refractive_index(cbs, wavelength(agb)) - refractive_index!(agb.children[1], 1, _n) - refractive_index!(agb.children[2], 1, _n) - return nothing - end - # Back prism interaction - if _shape === shape(cbs.back) - interaction = interact3d(system, cbs.back, agb, id) - hint!(interaction, Hint(cbs, shape(cbs.coating))) - return interaction - end + return CubeBeamsplitter{T, typeof(front), typeof(back)}(front, back) end \ No newline at end of file diff --git a/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl index 43d075e0c..a21e40e80 100644 --- a/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/PlateBeamsplitter.jl @@ -1,76 +1,59 @@ """ - AbstractPlateBeamsplitter <: AbstractBeamsplitter + AbstractPlateComponent <: AbstractObject -A generic type to represent an [`AbstractBeamsplitter`](@ref) that consists of a substrate with a -single coated face at which a beam splitting interaction occurs. - -# Implementation reqs. - -Subtypes of `AbstractPlateBeamsplitter` should implement all supertype reqs. as well as: - -## Fields - -- `coating`: a [`ThinBeamsplitter`](@ref) that represents the splitter coating -- `substrate`: a [`Prism`](@ref) that represents the substrate - -## Getters/setters - -If the concrete implementation does not define the above fields, the following getters must be defined: - -- `coating`: returns a [`ThinBeamsplitter`](@ref) -- `substrate`: returns a [`Prism`](@ref) - -# Additional information - -!!! info "Object orientation" - This `interact3d` method of this type strongly assumes that the coating is positioned directly upon - a single face of the substrate with a 100% fill factor. - -!!! info "Interaction logic" - This type uses the [`Hint`](@ref)-API in order to ensure that the splitting interaction is correctly - triggered at the coating. +Generic type for plate-like optical components. """ -abstract type AbstractPlateBeamsplitter{T} <: AbstractBeamsplitter{T} end - -coating(pbs::AbstractPlateBeamsplitter) = pbs.coating -substrate(pbs::AbstractPlateBeamsplitter) = pbs.substrate - -Base.position(pbs::AbstractPlateBeamsplitter) = position(coating(pbs)) - -orientation(pbs::AbstractPlateBeamsplitter) = orientation(substrate(pbs)) +abstract type AbstractPlateComponent{T} <: AbstractObject{T} end -shape_trait_of(::AbstractPlateBeamsplitter) = MultiShape() - -shape(pbs::AbstractPlateBeamsplitter) = (substrate(pbs), coating(pbs)) - -refractive_index(pbs::AbstractPlateBeamsplitter, λ::Real) = refractive_index(substrate(pbs), λ) +""" + AbstractPlateBeamsplitter <: AbstractRefractiveOptic +A generic type to represent an optical plate beamsplitter where beam splitting occurs at a coated surface face. """ - RectangularPlateBeamsplitter <: AbstractPlateBeamsplitter +abstract type AbstractPlateBeamsplitter{T, N} <: AbstractRefractiveOptic{T, N} end -A plate beamsplitter with rectangular substrate and a single coated face. -For more information refer to the [`AbstractPlateBeamsplitter`](@ref) docs. -# Fields +""" + RectangularPlateBeamsplitter{T, S, N, C} <: AbstractPlateBeamsplitter{T, N} -- `substrate`: a rectangular [`Prism`](@ref) that acts as the substrate -- `coating`: a [`ThinBeamsplitter`](@ref) that acts as the coating +A plate beamsplitter with a rectangular substrate and surface coatings. +""" +struct RectangularPlateBeamsplitter{T, S <: BoxSDF{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractPlateBeamsplitter{T, N} + shape::S + n::N + coatings::C + function RectangularPlateBeamsplitter( + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: BoxSDF{T}, N <: RefractiveIndex, C <: Tuple} + test_refractive_index_function(n) + return new{T, S, N, C}(shape, n, coatings) + end +end -# Additional information +""" + RoundPlateBeamsplitter{T, S, N, C} <: AbstractPlateBeamsplitter{T, N} -!!! info "Kinematic center" - The center of kinematics of this splitter lies at the center of the coating. +A plate beamsplitter with a cylindrical substrate and surface coatings. """ -struct RectangularPlateBeamsplitter{T} <: AbstractPlateBeamsplitter{T} - substrate::Prism{T, BoxSDF{T}} - coating::ThinBeamsplitter{T, Mesh{T}} +struct RoundPlateBeamsplitter{T, S <: PlanoSurfaceSDF{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractPlateBeamsplitter{T, N} + shape::S + n::N + coatings::C + function RoundPlateBeamsplitter( + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: PlanoSurfaceSDF{T}, N <: RefractiveIndex, C <: Tuple} + test_refractive_index_function(n) + return new{T, S, N, C}(shape, n, coatings) + end end +# Compatibility accessors +substrate(p::AbstractPlateBeamsplitter) = p +coating(p::AbstractPlateBeamsplitter) = get_matching_coating(coatings(p), shape(p), [0.0, 0.0, 0.0], [0.0, -1.0, 0.0]) + """ - RectangularPlateBeamsplitter(width, height, thickness, n; reflectance=0.5) + RectangularPlateBeamsplitter(width, height, thickness, n; reflectance=0.5, back_coating=nothing) -Creates a [`RectangularPlateBeamsplitter`](@ref). The splitter is aligned with the negative y-axis. -The splitter coating is centered at the origin. See also [`RoundPlateBeamsplitter`](@ref). +Creates a [`RectangularPlateBeamsplitter`](@ref). The splitter front face is centered at the origin, +with the substrate extending along the positive y-axis. # Inputs @@ -82,232 +65,77 @@ The splitter coating is centered at the origin. See also [`RoundPlateBeamsplitte # Keywords - `reflectance`: defines the splitting ratio in [-], i.e. R = 0 ... 1.0 +- `back_coating`: optional coating attached to the back face (e.g., [`SimpleARCoating`](@ref)) """ function RectangularPlateBeamsplitter( width::Real, height::Real, thickness::Real, n::RefractiveIndex; - reflectance::Real=0.5 + reflectance::Real=0.5, + back_coating=nothing ) - # create substrate prism and move into pos - substrate_shape = BoxSDF(width, thickness, height) - substrate = Prism(substrate_shape, n) - translate3d!(substrate, [0, thickness/2, 0]) - # rotate splitter "coating" into pos - coating = ThinBeamsplitter(width, height; reflectance) - zrotate3d!(coating, π) - return RectangularPlateBeamsplitter(substrate, coating) -end - -""" - RoundPlateBeamsplitter <: AbstractPlateBeamsplitter - -A plate beamsplitter with cylindrical substrate and a single coated face. -For more information refer to the [`AbstractPlateBeamsplitter`](@ref) docs. - -# Fields + if reflectance >= 1 || reflectance <= 0 + error("Splitting ratio ∈ (0, 1)!") + end + T = float(promote_type(typeof(width), typeof(height), typeof(thickness))) + substrate_shape = BoxSDF(T(width), T(thickness), T(height)) + translate3d!(substrate_shape, [T(0), T(thickness/2), T(0)]) -- `substrate`: a cylindrical [`Prism`](@ref) that acts as the substrate -- `coating`: a [`RoundThinBeamsplitter`](@ref) that acts as the coating + r = sqrt(reflectance) + t = sqrt(1.0 - reflectance) + coat_bs = SimpleBeamsplitterCoating(r, r, t, t) -# Additional information + coatings_list = if isnothing(back_coating) + (:front => coat_bs,) + else + (:front => coat_bs, :back => _coating_model(back_coating)) + end -!!! info "Kinematic center" - The center of kinematics of this splitter lies at the center of the coating. -""" -struct RoundPlateBeamsplitter{T} <: AbstractPlateBeamsplitter{T} - substrate::Prism{T, PlanoSurfaceSDF{T}} - coating::ThinBeamsplitter{T, Mesh{T}} + return RectangularPlateBeamsplitter(substrate_shape, n, coatings_list) end """ - RoundPlateBeamsplitter(diameter, thickness, n; reflectance=0.5) + RoundPlateBeamsplitter(diameter, thickness, n; reflectance=0.5, back_coating=nothing) -Creates a [`RoundPlateBeamsplitter`](@ref). The splitter is aligned with the negative y-axis. -The coating is centered at the origin. See also [`RectangularPlateBeamsplitter`](@ref). +Creates a circular [`RoundPlateBeamsplitter`](@ref). The splitter front face is centered at the origin, +with the substrate extending along the positive y-axis. # Inputs - `diameter`: x-z-plane substrate diameter in [m] -- `thickness`: substrate thickness along the z-axis in [m] +- `thickness`: substrate thickness along the y-axis in [m] - `n`: the [`RefractiveIndex`](@ref) of the substrate -# Keywords +# Keywords - `reflectance`: defines the splitting ratio in [-], i.e. R = 0 ... 1.0 +- `back_coating`: optional coating attached to the back face (e.g., [`SimpleARCoating`](@ref)) """ function RoundPlateBeamsplitter( diameter::Real, thickness::Real, n::RefractiveIndex; - reflectance::Real=0.5 + reflectance::Real=0.5, + back_coating=nothing ) - # create substrate cylinder prism - substrate_shape = PlanoSurfaceSDF(thickness, diameter) - substrate = Prism(substrate_shape, n) - # round splitter coating (neg. y-axi normals) - coating = RoundThinBeamsplitter(diameter; reflectance) - return RoundPlateBeamsplitter(substrate, coating) -end - -function intersect3d(pbs::AbstractPlateBeamsplitter, ray::AbstractRay) - # this is sooooooo stupid but necessary to ensure correct intersection... - ic = intersect3d(coating(pbs), ray) - is = intersect3d(substrate(pbs), ray) - if isnothing(ic) & isnothing(is) - return nothing - end - if isnothing(is) - object!(ic, pbs) - return ic - end - if isnothing(ic) - object!(is, pbs) - return is - end - # if both shapes are hit, pick the coating - if length(ic) ≈ length(is) - object!(ic, pbs) - return ic + if reflectance >= 1 || reflectance <= 0 + error("Splitting ratio ∈ (0, 1)!") end - if length(ic) < length(is) - object!(ic, pbs) - return ic + T = float(promote_type(typeof(diameter), typeof(thickness))) + substrate_shape = PlanoSurfaceSDF(T(thickness), T(diameter)) + + r = sqrt(reflectance) + t = sqrt(1.0 - reflectance) + coat_bs = SimpleBeamsplitterCoating(r, r, t, t) + + coatings_list = if isnothing(back_coating) + (:front => coat_bs,) else - object!(is, pbs) - return is + (:front => coat_bs, :back => _coating_model(back_coating)) end -end -function interact3d( - system::AbstractSystem, - pbs::AbstractPlateBeamsplitter, - beam::Beam{T, R}, - ray::R - ) where {T <: Real, R <: AbstractRay{T}} - # Substrate interaction - if shape(intersection(ray)) === shape(substrate(pbs)) - interaction = interact3d(system, substrate(pbs), beam, ray) - # Hint towards coating - hint!(interaction, Hint(pbs, shape(coating(pbs)))) - return interaction - end - # Splitter "coating" interaction - if shape(intersection(ray)) === shape(coating(pbs)) - # Beamsplitter coating interaction - interact3d(system, coating(pbs), beam, ray) - # Update refractive index and calculate refraction - λ = wavelength(ray) - n_optics = refractive_index(pbs, λ) - n_system = refractive_index(system, λ) - if isentering(ray) - # transmitted ray is refracted into substrate - _nt = n_optics - _nr = n_system - n_d, _ = refraction3d(ray, n_optics) - else - # transmitted ray is refracted into environment - _nt = n_system - _nr = n_optics - n_d, _ = refraction3d(ray, n_system) - end - refractive_index!(first(rays(beam.children[1])), _nt) - refractive_index!(first(rays(beam.children[2])), _nr) - direction!(first(rays(beam.children[1])), n_d) - return nothing - end - # if nothing worked, return nothing - return nothing + return RoundPlateBeamsplitter(substrate_shape, n, coatings_list) end -function interact3d( - system::AbstractSystem, - pbs::AbstractPlateBeamsplitter, - gauss::GaussianBeamlet, - id::Int - ) - _shape = shape(intersection(rays(gauss.chief)[id])) - # Substrate interaction - if _shape === shape(substrate(pbs)) - interaction = interact3d(system, substrate(pbs), gauss, id) - hint!(interaction, Hint(pbs, shape(coating(pbs)))) - return interaction - end - # Splitter interaction - if _shape === shape(coating(pbs)) - interact3d(system, coating(pbs), gauss, id) - # Update refractive index and calculate refraction - λ = wavelength(rays(gauss.chief)[id]) - n_optics = refractive_index(pbs, λ) - n_system = refractive_index(system, λ) - if isentering(gauss, id) - # transmitted ray is refracted into substrate - _nt = n_optics - _nr = n_system - n_c, _ = refraction3d(rays(gauss.chief)[id], n_optics) - n_w, _ = refraction3d(rays(gauss.waist)[id], n_optics) - n_d, _ = refraction3d(rays(gauss.divergence)[id], n_optics) - else - # transmitted ray is refracted into environment - _nt = n_system - _nr = n_optics - n_c, _ = refraction3d(rays(gauss.chief)[id], n_system) - n_w, _ = refraction3d(rays(gauss.waist)[id], n_system) - n_d, _ = refraction3d(rays(gauss.divergence)[id], n_system) - end - # Update children ref. index and dir. due to refraction - refractive_index!(gauss.children[1], 1, _nt) - refractive_index!(gauss.children[2], 1, _nr) - direction!(first(rays(gauss.children[1].chief)), n_c) - direction!(first(rays(gauss.children[1].waist)), n_w) - direction!(first(rays(gauss.children[1].divergence)), n_d) - return nothing - end - # if nothing worked, return nothing - return nothing -end -function interact3d( - system::AbstractSystem, - pbs::AbstractPlateBeamsplitter, - agb::AstigmaticGaussianBeamlet, - id::Int - ) - _shape = shape(intersection(rays(agb.c)[id])) - # Substrate interaction - if _shape === shape(substrate(pbs)) - interaction = interact3d(system, substrate(pbs), agb, id) - hint!(interaction, Hint(pbs, shape(coating(pbs)))) - return interaction - end - # Splitter interaction - if _shape === shape(coating(pbs)) - interact3d(system, coating(pbs), agb, id) - # Update refractive index and calculate refraction - λ = wavelength(rays(agb.c)[id]) - n_optics = refractive_index(pbs, λ) - n_system = refractive_index(system, λ) - if isentering(agb, id) - # transmitted ray is refracted into substrate - _nt = n_optics - _nr = n_system - else - # transmitted ray is refracted into environment - _nt = n_system - _nr = n_optics - end - # Update children ref. index - refractive_index!(agb.children[1], 1, _nt) - refractive_index!(agb.children[2], 1, _nr) - # Calculate refracted directions for transmitted child's component beams - n_target = isentering(agb, id) ? n_optics : n_system - for (beam, pbeam) in zip(_component_beams(agb.children[1]), _component_beams(agb)) - n_d, _ = refraction3d(rays(pbeam)[id], n_target) - direction!(first(rays(beam)), n_d) - end - return nothing - end - # if nothing worked, return nothing - return nothing -end diff --git a/src/OpticalComponents/Beamsplitters/PolarizingBeamSplitter.jl b/src/OpticalComponents/Beamsplitters/PolarizingBeamSplitter.jl new file mode 100644 index 000000000..fbef168c9 --- /dev/null +++ b/src/OpticalComponents/Beamsplitters/PolarizingBeamSplitter.jl @@ -0,0 +1,129 @@ +# Polarizing Beam Splitter (PBS) Components +# Reuses the generic Coating system under the hood with a SimpleBeamsplitterCoating. + +""" + PolarizingBeamSplitter(shape) + PolarizingBeamSplitter(width, height) + PolarizingBeamSplitter(diameter) + +Ideal polarizing plate that separates an incoming `PolarizedRay` into +transmitted and reflected beams. The device is represented by a zero-thickness +surface whose orientation sets the splitting axes: + +- local `x`-axis → transmitted (Ex) polarization component +- local `z`-axis → reflected (Ez) polarization component + +Rotate the underlying shape to align these axes with the desired global +polarization directions. Incoming rays are assumed to strike the plate from the +positive local `y` direction. +""" +function PolarizingBeamSplitter(shape::AbstractShape{T}) where {T} + J_t = XZBasis(one(T), zero(T), zero(T), zero(T)) + J_r = XZBasis(zero(T), zero(T), zero(T), -one(T)) + model = JonesCoating(J_t, J_r; behavior = Splitting()) + return Coating(shape, model) +end + +function PolarizingBeamSplitter(width::Real, height::Real) + T = float(promote_type(typeof(width), typeof(height))) + return PolarizingBeamSplitter(RectangularFlatMesh(T(width), T(height))) +end + +function PolarizingBeamSplitter(diameter::Real) + T = float(typeof(diameter)) + return PolarizingBeamSplitter(CircularFlatMesh(T(diameter) / 2)) +end + +#= +Plate Polarizing Beamsplitters +=# + +""" + RectangularPolarizingPlateBeamsplitter{T, S, N, C} <: AbstractPlateBeamsplitter{T, N} + +A plate beamsplitter with a rectangular substrate and an ideal polarizing splitting coating attached to its front face. +""" +struct RectangularPolarizingPlateBeamsplitter{T, S <: BoxSDF{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractPlateBeamsplitter{T, N} + shape::S + n::N + coatings::C + function RectangularPolarizingPlateBeamsplitter( + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: BoxSDF{T}, N <: RefractiveIndex, C <: Tuple} + test_refractive_index_function(n) + return new{T, S, N, C}(shape, n, coatings) + end +end + +""" + RoundPolarizingPlateBeamsplitter{T, S, N, C} <: AbstractPlateBeamsplitter{T, N} + +A plate beamsplitter with a cylindrical substrate and an ideal polarizing splitting coating attached to its front face. +""" +struct RoundPolarizingPlateBeamsplitter{T, S <: PlanoSurfaceSDF{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractPlateBeamsplitter{T, N} + shape::S + n::N + coatings::C + function RoundPolarizingPlateBeamsplitter( + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: PlanoSurfaceSDF{T}, N <: RefractiveIndex, C <: Tuple} + test_refractive_index_function(n) + return new{T, S, N, C}(shape, n, coatings) + end +end + +""" + RectangularPolarizingPlateBeamsplitter(width, height, thickness, n; back_coating=nothing) + +A plate beamsplitter with a rectangular substrate and an ideal polarizing splitting coating attached to its front face. +""" +function RectangularPolarizingPlateBeamsplitter( + width::Real, + height::Real, + thickness::Real, + n::RefractiveIndex; + back_coating=nothing +) + T = float(promote_type(typeof(width), typeof(height), typeof(thickness))) + substrate_shape = BoxSDF(T(width), T(thickness), T(height)) + translate3d!(substrate_shape, [T(0), T(thickness / 2), T(0)]) + + J_t = XZBasis(one(T), zero(T), zero(T), zero(T)) + J_r = XZBasis(zero(T), zero(T), zero(T), -one(T)) + coat_pbs = JonesCoating(J_t, J_r; behavior = Splitting()) + + coatings_list = if isnothing(back_coating) + (:front => coat_pbs,) + else + (:front => coat_pbs, :back => _coating_model(back_coating)) + end + + return RectangularPolarizingPlateBeamsplitter(substrate_shape, n, coatings_list) +end + +""" + RoundPolarizingPlateBeamsplitter(diameter, thickness, n; back_coating=nothing) + +A plate beamsplitter with a cylindrical substrate and an ideal polarizing splitting coating attached to its front face. +""" +function RoundPolarizingPlateBeamsplitter( + diameter::Real, + thickness::Real, + n::RefractiveIndex; + back_coating=nothing +) + T = float(promote_type(typeof(diameter), typeof(thickness))) + substrate_shape = PlanoSurfaceSDF(T(thickness), T(diameter)) + + J_t = XZBasis(one(T), zero(T), zero(T), zero(T)) + J_r = XZBasis(zero(T), zero(T), zero(T), -one(T)) + coat_pbs = JonesCoating(J_t, J_r; behavior = Splitting()) + + coatings_list = if isnothing(back_coating) + (:front => coat_pbs,) + else + (:front => coat_pbs, :back => _coating_model(back_coating)) + end + + return RoundPolarizingPlateBeamsplitter(substrate_shape, n, coatings_list) +end + + diff --git a/src/OpticalComponents/Beamsplitters/PolarizingCubeBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/PolarizingCubeBeamsplitter.jl new file mode 100644 index 000000000..63b0694e7 --- /dev/null +++ b/src/OpticalComponents/Beamsplitters/PolarizingCubeBeamsplitter.jl @@ -0,0 +1,55 @@ +struct PolarizingCubeBeamsplitterShape{T} <: AbstractShape{T} end + +""" + PolarizingCubeBeamsplitter <: AbstractBeamsplitter + +A cuboid polarizing beamsplitter where the splitting interaction occurs between two [`RightAnglePrism`](@ref)s. +For more information refer to the [`AbstractPlateBeamsplitter`](@ref) docs. + +# Fields + +- `front`: the forward facing substrate, represented by a coated prism (coated [`RightAnglePrism`](@ref)) +- `back`: the backward facing substrate, represented by a [`RightAnglePrism`](@ref) +""" +struct PolarizingCubeBeamsplitter{T, F, B} <: AbstractObjectGroup{T} + front::F + back::B +end + +shape_trait_of(::PolarizingCubeBeamsplitter) = MultiShape() + +shape(cbs::PolarizingCubeBeamsplitter) = (cbs.front, cbs.back) + +objects(cbs::PolarizingCubeBeamsplitter) = (cbs.front, cbs.back) + +refractive_index(cbs::PolarizingCubeBeamsplitter, λ::Real) = refractive_index(cbs.front, λ) + +""" + PolarizingCubeBeamsplitter(leg_length, n) + +Creates a [`PolarizingCubeBeamsplitter`](@ref). The cuboid is centered at the origin. The splitter +coating is orientated at a 45° angle with respect to the y-axis. + +# Inputs + +- `leg_length`: the x-, y- and z-edge length in [m] +- `n`: the [`RefractiveIndex`](@ref) of the front and back prism +""" +function PolarizingCubeBeamsplitter( + leg_length::Real, + n::RefractiveIndex + ) + T = float(typeof(leg_length)) + front_prism = RightAnglePrism(T(leg_length), T(leg_length), n) + back = RightAnglePrism(T(leg_length), T(leg_length), n) + zrotate3d!(back, deg2rad(180)) + + coat_bs = SimpleBeamsplitterCoating( + 1.0, 0.0, # rs, rp + 0.0, 1.0 # ts, tp + ) + + front = with_coatings(front_prism, :hypotenuse => coat_bs) + + return PolarizingCubeBeamsplitter{T, typeof(front), typeof(back)}(front, back) +end diff --git a/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl b/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl index 11d99d6ab..3aa31d461 100644 --- a/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl +++ b/src/OpticalComponents/Beamsplitters/ThinBeamsplitter.jl @@ -1,229 +1,48 @@ -""" - ThinBeamsplitter <: AbstractBeamsplitter - -Represents a 2D beam-splitting device. - -# Fields - -- `shape`: 2D [`AbstractShape`](@ref) at which the splitting process occurs (e.g. a 2D-[`Mesh`](@ref)) -- `reflectance`: scalar reflection factor -- `transmittance`: scalar transmission factor - -!!! warning - Note that the `transmittance` should be calculated from an input `reflectance` in order - to ensure that R² + T² = 1. -""" -struct ThinBeamsplitter{T <: Real, S <: AbstractShape{T}} <: AbstractBeamsplitter{T} - shape::S - reflectance::T - transmittance::T -end - -reflectance(bs::ThinBeamsplitter) = bs.reflectance -transmittance(bs::ThinBeamsplitter) = bs.transmittance +# Thin Beamsplitter Component +# Reuses the generic Coating system under the hood with a SimpleBeamsplitterCoating. """ + ThinBeamsplitter(shape; reflectance=0.5) ThinBeamsplitter(width, height; reflectance=0.5) - -Creates a zero-thickness, lossless, non-polarizing 2D rectangular [`ThinBeamsplitter`](@ref) where - -- `width`: is the x-dir. edge length in [m] -- `height`: is the z-dir. edge length in [m] -- `reflectance`: kw-arg that determines how much light is **reflected**, i.e. 0.7 for a 70:30 splitter - -# Additional information - -!!! info "Reflectance" - The input value for the `reflectance` R is normed such that R² + T² = 1, where T is the `transmittance`. - The transmittance is calculated via T = √(1 - R²). - -!!! warning "Reflection phase jump" - Note that the reflection phase jump θᵣ is implemented by the individual [`interact3d`](@ref)-methods. Refer to them for more information. -""" -function ThinBeamsplitter(width::Real, height::Real; reflectance::Real = 0.5) - if reflectance ≥ 1 || reflectance ≈ 0 - error("Splitting ratio ∈ (0, 1)!") - end - shape = RectangularFlatMesh(width, height) - Reflected = sqrt(reflectance) - Transmitted = sqrt(1 - Reflected^2) - return ThinBeamsplitter(shape, Reflected, Transmitted) -end - -""" RoundThinBeamsplitter(diameter; reflectance=0.5) -Creates a zero-thickness, 2D round [`ThinBeamsplitter`](@ref) with the specified `diameter` in [m]. -For more information, refer to the [`ThinBeamsplitter`](@ref) constructor. +Creates a zero-thickness, lossless, non-polarizing 2D rectangular or circular beamsplitter. """ -function RoundThinBeamsplitter(diameter::Real; reflectance::Real = 0.5) - if reflectance ≥ 1 || reflectance ≈ 0 +function ThinBeamsplitter(shape::AbstractShape{T}; reflectance::Real = 0.5) where {T} + if reflectance >= 1 || reflectance <= 0 error("Splitting ratio ∈ (0, 1)!") end - shape = CircularFlatMesh(diameter / 2) - R = sqrt(reflectance) - T = sqrt(1 - R^2) - return ThinBeamsplitter(shape, R, T) -end - -function ThinBeamsplitter(width::Real; reflectance::Real = 0.5) - ThinBeamsplitter(width, width; reflectance) -end - -Base.isvalid(bs::AbstractBeamsplitter) = reflectance(bs)^2 + transmittance(bs)^2 ≈ 1 - -@inline function _beamsplitter_transmitted_beam( - ::AbstractBeamsplitter, ::Beam{T, R}, ray::R) where {T <: Real, R <: Ray{T}} - pos = position(ray) + length(ray) * direction(ray) - dir = direction(ray) - return Beam(Ray(pos, dir, wavelength(ray))) + r = sqrt(reflectance) + t = sqrt(1 - reflectance) + model = SimpleBeamsplitterCoating(r, r, t, t) # rs, rp, ts, tp + return Coating(shape, model) end -@inline function _beamsplitter_reflected_beam( - ::AbstractBeamsplitter, ::Beam{T, R}, ray::R) where {T <: Real, R <: Ray{T}} - normal = normal3d(intersection(ray)) - pos = position(ray) + length(ray) * direction(ray) - dir = reflection3d(direction(ray), normal) - return Beam(Ray(pos, dir, wavelength(ray))) -end - -@inline function _beamsplitter_transmitted_beam(bs::AbstractBeamsplitter, ::Beam{T, R}, - ray::R) where {T <: Real, R <: PolarizedRay{T}} - J = SPBasis(transmittance(bs), 0, 0, transmittance(bs)) - pos = position(ray) + length(ray) * direction(ray) - dir = direction(ray) - E0 = _calculate_global_E0(bs, ray, dir, J) - return Beam(PolarizedRay(pos, dir, wavelength(ray), E0)) -end - -@inline function _beamsplitter_reflected_beam(bs::AbstractBeamsplitter, ::Beam{T, R}, - ray::R) where {T <: Real, R <: PolarizedRay{T}} - J = SPBasis(-reflectance(bs), 0, 0, reflectance(bs)) - normal = normal3d(intersection(ray)) - pos = position(ray) + length(ray) * direction(ray) - in_dir = direction(ray) - out_dir = reflection3d(in_dir, normal) - E0 = _calculate_global_E0(bs, ray, out_dir, J) - return Beam(PolarizedRay(pos, out_dir, wavelength(ray), E0)) -end - -function interact3d(::AbstractSystem, bs::ThinBeamsplitter, beam::Beam{T, R}, - ray::R) where {T <: Real, R <: AbstractRay{T}} - # Push transmitted and reflected beams to system - children!(beam, - [_beamsplitter_transmitted_beam(bs, beam, ray), - _beamsplitter_reflected_beam(bs, beam, ray)]) - # Stop for beam spawning - return nothing -end - -@inline function _beamsplitter_transmitted_beam( - bs::AbstractBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) - # Transmitted Gaussian (no phase flip) - chief = _beamsplitter_transmitted_beam(bs, gauss.chief, rays(gauss.chief)[ray_id]) - waist = _beamsplitter_transmitted_beam(bs, gauss.waist, rays(gauss.waist)[ray_id]) - divergence = _beamsplitter_transmitted_beam( - bs, gauss.divergence, rays(gauss.divergence)[ray_id]) - λ = wavelength(gauss) - w0 = gauss_parameters(gauss, length(gauss))[4] - E0 = transmittance(bs) * electric_field(gauss) * (beam_waist(gauss) / w0) - return GaussianBeamlet(chief, waist, divergence, λ, w0, E0) +function ThinBeamsplitter(width::Real, height::Real; reflectance::Real = 0.5) + T = float(promote_type(typeof(width), typeof(height))) + return ThinBeamsplitter(RectangularFlatMesh(T(width), T(height)); reflectance = T(reflectance)) end -@inline function _beamsplitter_reflected_beam( - bs::AbstractBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) - # Reflected Gaussian (no phase flip) - chief = _beamsplitter_reflected_beam(bs, gauss.chief, rays(gauss.chief)[ray_id]) - waist = _beamsplitter_reflected_beam(bs, gauss.waist, rays(gauss.waist)[ray_id]) - divergence = _beamsplitter_reflected_beam( - bs, gauss.divergence, rays(gauss.divergence)[ray_id]) - λ = wavelength(gauss) - w0 = gauss_parameters(gauss, length(gauss))[4] - E0 = reflectance(bs) * electric_field(gauss) * (beam_waist(gauss) / w0) - return GaussianBeamlet(chief, waist, divergence, λ, w0, E0) +function ThinBeamsplitter(width::Real; reflectance::Real = 0.5) + return ThinBeamsplitter(width, width; reflectance) end """ - interact3d(::AbstractSystem, bs::ThinBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) - -Models the interaction between a [`ThinBeamsplitter`](@ref) and a [`GaussianBeamlet`](@ref). - -# Reflection phase jump + RoundThinBeamsplitter(diameter; reflectance=0.5) -The reflection phase jump is modeled here as θᵣ = π for simplicity. This is since in practice it will have only a relative effect on the signal at the detector for interferometric setups. -The phase jump is applied to the reflected portion of any incoming beam that faces the [`ThinBeamsplitter`](@ref) normal vector, which assumes that the splitter has an unambigous normal, i.e. a 2D mesh. -This is intended to model the effect of the Fresnel equations without full polarization calculus. +Creates a circular [`ThinBeamsplitter`](@ref). """ -function interact3d( - ::AbstractSystem, bs::ThinBeamsplitter, gauss::GaussianBeamlet, ray_id::Int) - # Phase flip - ray = gauss.chief.rays[ray_id] - df = dot(direction(ray), normal3d(intersection(ray))) - if df < 0 - ϕ = π - else - ϕ = 0 - end - - t = _beamsplitter_transmitted_beam(bs, gauss, ray_id) - r = _beamsplitter_reflected_beam(bs, gauss, ray_id) - - # Add conditional phase flip to reflected beam - electric_field!(r, electric_field(r) * exp(im * ϕ)) - - children!(gauss, [t, r]) - return nothing -end - -@inline function _beamsplitter_transmitted_beam( - bs::AbstractBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) - c = _beamsplitter_transmitted_beam(bs, agb.c, rays(agb.c)[ray_id]) - wxp = _beamsplitter_transmitted_beam(bs, agb.wxp, rays(agb.wxp)[ray_id]) - wxm = _beamsplitter_transmitted_beam(bs, agb.wxm, rays(agb.wxm)[ray_id]) - wyp = _beamsplitter_transmitted_beam(bs, agb.wyp, rays(agb.wyp)[ray_id]) - wym = _beamsplitter_transmitted_beam(bs, agb.wym, rays(agb.wym)[ray_id]) - dxp = _beamsplitter_transmitted_beam(bs, agb.dxp, rays(agb.dxp)[ray_id]) - dxm = _beamsplitter_transmitted_beam(bs, agb.dxm, rays(agb.dxm)[ray_id]) - dyp = _beamsplitter_transmitted_beam(bs, agb.dyp, rays(agb.dyp)[ray_id]) - dym = _beamsplitter_transmitted_beam(bs, agb.dym, rays(agb.dym)[ray_id]) - return AstigmaticGaussianBeamlet(c, wxp, wxm, wyp, wym, dxp, dxm, dyp, dym) +function RoundThinBeamsplitter(diameter::Real; reflectance::Real = 0.5) + T = float(typeof(diameter)) + return ThinBeamsplitter(CircularFlatMesh(T(diameter) / 2); reflectance = T(reflectance)) end -@inline function _beamsplitter_reflected_beam( - bs::AbstractBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) - c = _beamsplitter_reflected_beam(bs, agb.c, rays(agb.c)[ray_id]) - wxp = _beamsplitter_reflected_beam(bs, agb.wxp, rays(agb.wxp)[ray_id]) - wxm = _beamsplitter_reflected_beam(bs, agb.wxm, rays(agb.wxm)[ray_id]) - wyp = _beamsplitter_reflected_beam(bs, agb.wyp, rays(agb.wyp)[ray_id]) - wym = _beamsplitter_reflected_beam(bs, agb.wym, rays(agb.wym)[ray_id]) - dxp = _beamsplitter_reflected_beam(bs, agb.dxp, rays(agb.dxp)[ray_id]) - dxm = _beamsplitter_reflected_beam(bs, agb.dxm, rays(agb.dxm)[ray_id]) - dyp = _beamsplitter_reflected_beam(bs, agb.dyp, rays(agb.dyp)[ray_id]) - dym = _beamsplitter_reflected_beam(bs, agb.dym, rays(agb.dym)[ray_id]) - return AstigmaticGaussianBeamlet(c, wxp, wxm, wyp, wym, dxp, dxm, dyp, dym) +# Check validity of the split coefficients +function Base.isvalid(c::Coating{<:Any, <:Any, <:SimpleBeamsplitterCoating}) + model = c.model + return abs2(model.rs) + abs2(model.ts) ≈ 1 end -""" - interact3d(::AbstractSystem, bs::ThinBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) - -Models the interaction between a [`ThinBeamsplitter`](@ref) and an [`AstigmaticGaussianBeamlet`](@ref). -The reflection phase jump θᵣ = π is applied to the reflected child beam. -""" -function interact3d( - ::AbstractSystem, bs::ThinBeamsplitter, agb::AstigmaticGaussianBeamlet, ray_id::Int) - # Phase flip - ray = rays(agb.c)[ray_id] - df = dot(direction(ray), normal3d(intersection(ray))) - ϕ = df < 0 ? π : 0 - - t = _beamsplitter_transmitted_beam(bs, agb, ray_id) - r = _beamsplitter_reflected_beam(bs, agb, ray_id) - - # Add conditional phase flip to reflected beam chief polarization - chief_ray = first(rays(r.c)) - E_new = polarization(chief_ray) * exp(im * ϕ) - polarization!(chief_ray, E_new) - - children!(agb, [t, r]) - return nothing +function Base.isvalid(model::SimpleBeamsplitterCoating) + return abs2(model.rs) + abs2(model.ts) ≈ 1 end diff --git a/src/OpticalComponents/Detectors/Detector.jl b/src/OpticalComponents/Detectors/Detector.jl index b8296cdb2..e63cf758f 100644 --- a/src/OpticalComponents/Detectors/Detector.jl +++ b/src/OpticalComponents/Detectors/Detector.jl @@ -301,6 +301,9 @@ end function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, ray::R) where {T <: Real, R <: Ray{T}} + # Apply bulk attenuation over the final segment arriving at the detector + att_power, _ = bulk_attenuation_factor(refractive_index(ray), wavelength(ray), length(ray)) + weight!(ray, weight(ray) * att_power) # Optical path length and wavenumber opl = optical_path_length(beam) # Push hit data into detector, determine stop @@ -318,7 +321,8 @@ function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, direction(hit), nothing, wavelength(ray), - refractive_index(ray) + refractive_index(ray), + weight(ray) ) ) end @@ -326,6 +330,9 @@ end function interact3d(::AbstractSystem, d::Detector, beam::Beam{T, R}, ray::R) where {T <: Real, R <: PolarizedRay{T}} + # Apply bulk attenuation over the final segment arriving at the detector + _, att_field = bulk_attenuation_factor(refractive_index(ray), wavelength(ray), length(ray)) + polarization!(ray, polarization(ray) * att_field) # Optical path length and wavenumber opl = optical_path_length(beam) # Push hit data into detector, determine stop diff --git a/src/OpticalComponents/Detectors/DetectorUtils.jl b/src/OpticalComponents/Detectors/DetectorUtils.jl index b4b8ef8f6..688e17a90 100644 --- a/src/OpticalComponents/Detectors/DetectorUtils.jl +++ b/src/OpticalComponents/Detectors/DetectorUtils.jl @@ -102,10 +102,10 @@ function calc_local_pos( # Calculate waist projections in local (x, z) coordinates ts = LinRange(0, 2pi, num_spots) p0 = position(pd) - # Left-handed coord. sys. due to pd mesh rotation - ex = -orientation(pd)[:,1] - ey = orientation(pd)[:,2] - ez = orientation(pd)[:,3] + orient = orientation(pd) + ex = Point3(-orient[1, 1], -orient[2, 1], -orient[3, 1]) + ey = Point3(orient[1, 2], orient[2, 2], orient[3, 2]) + ez = Point3(orient[1, 3], orient[2, 3], orient[3, 3]) pts_2D = Vector{Point2{T}}() sizehint!(pts_2D, length(hits) * num_spots) @@ -157,10 +157,10 @@ function calc_local_pos( # Calculate waist projections in local (x, z) coordinates ts = LinRange(0, 2pi, num_spots) p0 = position(pd) - # Left-handed coord. sys. due to pd mesh rotation - ex = -orientation(pd)[:,1] - ey = orientation(pd)[:,2] - ez = orientation(pd)[:,3] + orient = orientation(pd) + ex = Point3(-orient[1, 1], -orient[2, 1], -orient[3, 1]) + ey = Point3(orient[1, 2], orient[2, 2], orient[3, 2]) + ez = Point3(orient[1, 3], orient[2, 3], orient[3, 3]) pts_2D = Vector{Point2{T}}() sizehint!(pts_2D, length(hits) * num_spots) diff --git a/src/OpticalComponents/Detectors/FieldCalculation.jl b/src/OpticalComponents/Detectors/FieldCalculation.jl index b8a8d768a..9897d742c 100644 --- a/src/OpticalComponents/Detectors/FieldCalculation.jl +++ b/src/OpticalComponents/Detectors/FieldCalculation.jl @@ -88,30 +88,31 @@ function electric_field( local_z = Point3(orientation(pd)[:, 3]) origin = position(pd) # Calculate field superposition - Threads.@threads for j in eachindex(zs) - z_grid = zs[j] - # Hoist z-grid math out of inner loop - p_row = origin + z_grid * local_z - - @inbounds for i in eachindex(xs) - x_grid = xs[i] - p1 = p_row + x_grid * local_x - - acc = Complex{G}(0.0) - for hit in hits - v = p1 - hit.p0 - l1 = _pseudo_dot(v, hit.d0) - - # Transverse distance r - r_vec = v - l1 * hit.d0 + for hit in hits + # Pre-compute hit constants + p0 = hit.p0 + d0 = hit.d0 + gauss = hit.gauss + l0 = hit.l0 + id = hit.id + sqrt_proj = hit.sqrt_proj + + Threads.@threads for j in eachindex(zs) + z_grid = zs[j] + p_row = origin + z_grid * local_z + + @inbounds for i in eachindex(xs) + x_grid = xs[i] + p1 = p_row + x_grid * local_x + + v = p1 - p0 + l1 = _pseudo_dot(v, d0) + r_vec = v - l1 * d0 r = norm(r_vec) + z = l0 + l1 - # Distance along beam - z = hit.l0 + l1 - - acc += electric_field(hit.gauss, r, z; hint = (hit.p0 + l1 * hit.d0, hit.id)) * hit.sqrt_proj + field[i, j] += electric_field(gauss, r, z; hint = (p0 + l1 * d0, id)) * sqrt_proj end - field[i, j] = acc end end return xs, zs, field @@ -150,42 +151,52 @@ function electric_field( local_x = Point3(-orientation(pd)[:, 1]) local_z = Point3(orientation(pd)[:, 3]) origin = position(pd) - # Calculate field superposition - Threads.@threads for j in eachindex(zs) - z_grid = zs[j] - # Hoist z-grid math out of inner loop - p_row = origin + z_grid * local_z - @inbounds for i in eachindex(xs) - x_grid = xs[i] - p1 = p_row + x_grid * local_x - - acc = Complex{G}(0.0) - for hit in hits - v = p1 - hit.p0 - l1 = _pseudo_dot(v, hit.d0) - r_vec = v - l1 * hit.d0 - - h1_z = hit.h1 + l1 * hit.u1 - h2_z = hit.h2 + l1 * hit.u2 - area_z = _pseudo_cross2d(h1_z, h2_z, hit.d0) + # Calculate field superposition with hoisted hit invariants + for hit in hits + d0 = hit.d0 + h1 = hit.h1 + u1 = hit.u1 + h2 = hit.h2 + u2 = hit.u2 + p0 = hit.p0 + l0 = hit.l0 + k0 = hit.k0 + Δl = hit.Δl + n_eff = hit.n_eff + area_ref = hit.area_ref + E_ref_amp = hit.E_ref_amp + sqrt_proj = hit.sqrt_proj + + Threads.@threads for j in eachindex(zs) + z_grid = zs[j] + p_row = origin + z_grid * local_z + + @inbounds for i in eachindex(xs) + x_grid = xs[i] + p1 = p_row + x_grid * local_x + + v = p1 - p0 + l1 = _pseudo_dot(v, d0) + r_vec = v - l1 * d0 + + h1_z = h1 + l1 * u1 + h2_z = h2 + l1 * u2 + area_z = _pseudo_cross2d(h1_z, h2_z, d0) if abs(area_z) < 1e-25 area_z = Complex{G}(1e-25, 1e-25) end - ξ1 = _pseudo_cross2d(h1_z, r_vec, hit.d0) - ξ2 = _pseudo_cross2d(h2_z, r_vec, hit.d0) - w = (ξ1 * _pseudo_dot(hit.u2, r_vec) - - ξ2 * _pseudo_dot(hit.u1, r_vec)) / (2 * area_z) + ξ1 = _pseudo_cross2d(h1_z, r_vec, d0) + ξ2 = _pseudo_cross2d(h2_z, r_vec, d0) + w = (ξ1 * _pseudo_dot(u2, r_vec) - ξ2 * _pseudo_dot(u1, r_vec)) / (2 * area_z) - phase_corr = (hit.n_eff - 1) * l1 - z_total = hit.l0 + l1 - ψ = sqrt(hit.area_ref / area_z) * - cis(hit.k0 * (z_total + w + hit.Δl + phase_corr)) + phase_corr = (n_eff - 1) * l1 + z_total = l0 + l1 + ψ = sqrt(area_ref / area_z) * cis(k0 * (z_total + w + Δl + phase_corr)) - acc += (hit.E_ref_amp * ψ) * hit.sqrt_proj + field[i, j] += (E_ref_amp * ψ) * sqrt_proj end - field[i, j] = acc end end return xs, zs, field @@ -193,7 +204,8 @@ end function electric_field( pd::Detector, - hits::Vector{RayHit{R}}; + hits::Vector{<:AbstractRayHit{R}}; + # kwargs n::Int = 100, crop_factor::Real = 1, diff --git a/src/OpticalComponents/DoubletLenses.jl b/src/OpticalComponents/DoubletLenses.jl index 264f2c605..abb61cd24 100644 --- a/src/OpticalComponents/DoubletLenses.jl +++ b/src/OpticalComponents/DoubletLenses.jl @@ -4,7 +4,7 @@ abstract type AbstractDoubletRefractiveOptic{ B <: AbstractShape{T}, N1 <: RefractiveIndex, N2 <: RefractiveIndex -} <: AbstractRefractiveOptic{T, N1} end +} <: AbstractObjectGroup{T} end """ DoubletLens @@ -23,22 +23,41 @@ See also [`SphericalDoubletLens`](@ref). This component type strongly assumes that both lenses are mounted fully flush with respect to each other. Gaps between the components might lead to incorrect results. """ -struct DoubletLens{T, F<:AbstractShape{T}, B<:AbstractShape{T}, N1<:RefractiveIndex, N2<:RefractiveIndex} <: AbstractDoubletRefractiveOptic{T, F, B, N1, N2} - front::Lens{T, F, N1} - back::Lens{T, B, N2} +struct DoubletLens{T, F <: AbstractRefractiveOptic{T}, B <: AbstractRefractiveOptic{T}} <: AbstractObjectGroup{T} + front::F + back::B + + function DoubletLens(front::F, back::B; front_coating = nothing, back_coating = nothing) where {T, F <: AbstractRefractiveOptic{T}, B <: AbstractRefractiveOptic{T}} + f_coated = !isnothing(front_coating) ? with_coatings(front; front = front_coating) : front + b_coated = !isnothing(back_coating) ? with_coatings(back; back = back_coating) : back + + # Check if they are flush and aligned along the optical axis + rel_pos = position(b_coated) - position(f_coated) + opt_axis = orientation(f_coated)[:, 2] + expected_offset = thickness(f_coated) + if !isapprox(rel_pos, expected_offset * opt_axis, atol=1e-5) + @warn "Doublet components are not aligned flush along the optical axis (expected offset $(expected_offset)m along orientation axis, got $(rel_pos)m). Ensure they were created in the default orientation before assembly. This may cause tracing errors at coincident boundaries." + end + if !isapprox(orientation(f_coated), orientation(b_coated), atol=1e-5) + @warn "Doublet components do not have matching orientation. Ensure they were created in the default orientation before assembly. This may cause tracing errors at coincident boundaries." + end + return new{T, typeof(f_coated), typeof(b_coated)}(f_coated, b_coated) + end end shape_trait_of(::DoubletLens) = MultiShape() shape(dl::DoubletLens) = (dl.front, dl.back) +objects(dl::DoubletLens) = (dl.front, dl.back) + Base.position(dl::DoubletLens) = position(dl.front) orientation(dl::DoubletLens) = orientation(dl.front) thickness(dl::DoubletLens) = thickness(shape(dl.front)) + thickness(shape(dl.back)) """ - SphericalDoubletLens(r1, r2, r3, l1, l2, d, n1, n2) + SphericalDoubletLens(r1, r2, r3, l1, l2, d, n1, n2; front_coating=nothing, back_coating=nothing) Generates a two-component "cemented" doublet lens consisting of two spherical lenses. For radii sign definition, refer to the [`SphericalLens`](@ref) constructor. @@ -52,25 +71,37 @@ For radii sign definition, refer to the [`SphericalLens`](@ref) constructor. - `l2`: second lens thickness - `d`: lens diameter - `n1`: first lens [`RefractiveIndex`](@ref) -- `n1`: second lens [`RefractiveIndex`](@ref) +- `n2`: second lens [`RefractiveIndex`](@ref) +- `front_coating`: optional coating model for front surface +- `back_coating`: optional coating model for back surface """ -function SphericalDoubletLens(r1, r2, r3, l1, l2, d, n1, n2) +function SphericalDoubletLens(r1, r2, r3, l1, l2, d, n1, n2; front_coating = nothing, back_coating = nothing) # Generate "cemented" front and back spherical lenses front = SphericalLens(r1, r2, l1, d, n1) back = SphericalLens(r2, r3, l2, d, n2) # Move doublet parts into position translate3d!(back, [0, thickness(shape(front)), 0]) - return DoubletLens(front, back) + return DoubletLens(front, back; front_coating = front_coating, back_coating = back_coating) end -function interact3d(system::AbstractSystem, dl::DoubletLens, beam::Beam{T, R}, ray::R) where {T <: Real, R <: Ray{T}} - # Interaction logic: if front is hit, hint to back and vice versa - if shape(intersection(ray)) === shape(dl.front) - i = interact3d(system, dl.front, beam, ray) - hint = Hint(dl, dl.back.shape) - elseif shape(intersection(ray)) === shape(dl.back) - i = interact3d(system, dl.back, beam, ray) - hint = Hint(dl, dl.front.shape) - end - return BeamInteraction(hint, i.ray) +""" + AsphericalDoubletLens(r1, r2, r3, l1, l2, d, n1, n2; k1=0, k2=0, k3=0, front_coating=nothing, back_coating=nothing) + +Generates a two-component "cemented" doublet lens consisting of two aspherical lens elements with conic constants `k1`, `k2`, and `k3`. +""" +@inline _to_refractive_index(n::Real) = (λ -> n) +@inline _to_refractive_index(n) = test_refractive_index_function(n) + +function AsphericalDoubletLens( + r1, r2, r3, l1, l2, d, n1, n2; + k1 = 0, k2 = 0, k3 = 0, + front_coating = nothing, back_coating = nothing +) + s1 = EvenAsphericalSurface(r1, d, k1, Float64[0.0]) + s2 = EvenAsphericalSurface(r2, d, k2, Float64[0.0]) + s3 = EvenAsphericalSurface(r3, d, k3, Float64[0.0]) + front = Lens(s1, s2, l1, _to_refractive_index(n1)) + back = Lens(s2, s3, l2, _to_refractive_index(n2)) + translate3d!(back, [0, thickness(shape(front)), 0]) + return DoubletLens(front, back; front_coating = front_coating, back_coating = back_coating) end \ No newline at end of file diff --git a/src/OpticalComponents/Lenses.jl b/src/OpticalComponents/Lenses.jl index a6897eb7e..6298d88a8 100644 --- a/src/OpticalComponents/Lenses.jl +++ b/src/OpticalComponents/Lenses.jl @@ -35,7 +35,9 @@ by specialized subtypes. abstract type AbstractRefractiveOptic{T, F} <: AbstractObject{T} end refractive_index(object::AbstractRefractiveOptic) = object.n -refractive_index(object::AbstractRefractiveOptic{<:Any, <:RefractiveIndex}, λ::Real)::Float64 = object.n(λ) +refractive_index(object::AbstractRefractiveOptic{<:Any, <:RefractiveIndex}, λ::Real) = object.n(λ) + +is_refractive(::AbstractRefractiveOptic) = true """ interact3d(AbstractSystem, AbstractRefractiveOptic, Beam, Ray) @@ -45,84 +47,11 @@ At the critical angle, total internal reflection occurs (see [`refraction3d`](@r """ function interact3d(system::AbstractSystem, optic::AbstractRefractiveOptic, - ::Beam{T, R}, - ray::R) where {T <: Real, R <: Ray{T}} - # Check dir. of ray and surface normal - normal = normal3d(intersection(ray)) - lambda = wavelength(ray) - if isentering(ray) - # Entering optic - n1 = refractive_index(ray) - n2 = refractive_index(optic, lambda) - # Hint to test optic again - hint = Hint(optic) - else - # Exiting optic - n1 = refractive_index(optic, lambda) - n2 = refractive_index(system, lambda) - hint = nothing - # Flip normal for refraction3d - normal = -normal - end - # Calculate new dir. and pos. - ndir, TIR = refraction3d(direction(ray), normal, n1, n2) - npos = position(ray) + length(ray) * direction(ray) - # In case of TIR, update hint and n2 - if TIR - hint = Hint(optic) - n2 = refractive_index(optic, lambda) - end - return BeamInteraction{T, R}(hint, - Ray{T}(npos, ndir, nothing, wavelength(ray), n2)) -end - -""" - interact3d(AbstractSystem, AbstractRefractiveOptic, Beam, PolarizedRay) - -Implements the refraction of a [`PolarizedRay`](@ref) at an uncoated optical surface. The "outside" ref. index is obtained from the `system` unless specified otherwise. -Reflection and transmission values are calculated via the [`fresnel_coefficients`](@ref). Stray light is not tracked. -In the case of total internal reflection, only the reflected light is traced. -""" -function interact3d(system::AbstractSystem, optic::AbstractRefractiveOptic, - ::Beam{T, R}, ray::R) where {T <: Real, R <: PolarizedRay{T}} - lambda = wavelength(ray) - normal = normal3d(intersection(ray)) - raypos = position(ray) + length(ray) * direction(ray) - if isentering(ray) - # Entering optic - n1 = refractive_index(ray) - n2 = refractive_index(optic, lambda) - # Hint to test optic again - hint = Hint(optic) - else - # Exiting optic - n1 = refractive_index(optic, lambda) - n2 = refractive_index(system, lambda) - hint = nothing - # Flip normal for refraction3d - normal = -normal - end - # Calculate (and correct into 1. quadrant) the angle of incidence - θi = angle3d(direction(ray), -normal) - # Get Fresnel coefficients - rs, rp, ts, tp = fresnel_coefficients(θi, n2 / n1) - # Optical interaction - if is_internally_reflected(rp, rs) - # Update hint and outgoing ref. index - hint = Hint(optic) - n2 = refractive_index(optic, lambda) - # Calculate reflection - new_dir = reflection3d(direction(ray), normal) - J = SPBasis(-rs, 0, 0, rp) - else - # Calculate refraction - new_dir, ~ = refraction3d(direction(ray), normal, n1, n2) - J = SPBasis(ts, 0, 0, tp) - end - # Calculate new polarization - E0 = _calculate_global_E0(optic, ray, new_dir, J) - return BeamInteraction{T, R}( - hint, PolarizedRay{T}(raypos, new_dir, nothing, wavelength(ray), n2, E0)) + beam::Beam{T, R}, + ray::R) where {T <: Real, R <: AbstractRay{T}} + coated_obj, coating = resolve_coated_boundary(system, optic, ray) + target_obj = isnothing(coated_obj) ? optic : coated_obj + return interact_refractive_boundary(system, target_obj, coating, beam, ray) end """ @@ -143,13 +72,14 @@ Refer to the [`Lens`](@ref) and [`SphericalLens`](@ref) constructors for more in and must be provided by the user. For testing purposes, an anonymous function, e.g. λ -> 1.5 can be passed such that the lens has the same refractive index for all wavelengths. """ -struct Lens{T, S <: AbstractShape{T}, N <: RefractiveIndex} <: AbstractRefractiveOptic{T, N} +struct Lens{T, S <: AbstractShape{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractRefractiveOptic{T, N} shape::S n::N + coatings::C function Lens( - shape::S, n::N) where {T <: Real, S <: AbstractShape{T}, N <: RefractiveIndex} + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: AbstractShape{T}, N <: RefractiveIndex, C <: Tuple} test_refractive_index_function(n) - return new{T, S, N}(shape, n) + return new{T, S, N, C}(shape, n, coatings) end end @@ -241,7 +171,8 @@ function Lens( end ring = RingSDF(d_front / 2, (d_back - d_front) / 2, leveling_thickness) - translate3d!(ring, [0, edge_sag(front_surface, front) + leveling_thickness / 2, 0]) + translate3d!(ring, + [0, edge_sag(front_surface, front) + leveling_thickness / 2, 0]) shape += ring else # d_front > d_back # Step exists on the back side: level back to match front. @@ -255,12 +186,14 @@ function Lens( end end leveling_center = position(mid)[2] + - (l0/2 + (back !== nothing ? edge_sag(back_surface, back) : 0)) + (l0 / 2 + + (back !== nothing ? edge_sag(back_surface, back) : + 0)) if back !== nothing leveling_center += s_back / 2 end ring = RingSDF(d_back / 2, (d_front - d_back) / 2, leveling_thickness) - translate3d!(ring, [0, thickness(front) + leveling_thickness/2, 0]) + translate3d!(ring, [0, thickness(front) + leveling_thickness / 2, 0]) shape += ring end end diff --git a/src/OpticalComponents/Mirrors.jl b/src/OpticalComponents/Mirrors.jl index 8024184e4..ad72cc58c 100644 --- a/src/OpticalComponents/Mirrors.jl +++ b/src/OpticalComponents/Mirrors.jl @@ -29,43 +29,38 @@ by specialized subtypes. """ abstract type AbstractReflectiveOptic{T} <: AbstractObject{T} end -# FIXME Require reflectivity field/function for interaction with PolarizedRay +@inline function resolve_coincident_boundary( + exiting_int, entering_int, ::AbstractObject, ::AbstractReflectiveOptic) + entering_int.coincident_object = object(exiting_int) + return entering_int +end -""" - interact3d(AbstractReflectiveOptic, Ray) +@inline function resolve_coincident_boundary( + exiting_int, entering_int, ::AbstractReflectiveOptic, ::AbstractObject) + exiting_int.coincident_object = object(entering_int) + return exiting_int +end -Implements the reflection of a [`Ray`](@ref) via the normal at the intersection point on an optical surface. -""" -function interact3d(::AbstractSystem, - ::AbstractReflectiveOptic, - ::Beam{T, R}, - ray::R) where {T <: Real, R <: Ray{T}} - normal = normal3d(intersection(ray)) - npos = position(ray) + length(ray) * direction(ray) - ndir = reflection3d(direction(ray), normal) - return BeamInteraction{T, R}(nothing, - Ray{T}(npos, ndir, nothing, wavelength(ray), refractive_index(ray))) +@inline function resolve_coincident_boundary( + exiting_int, entering_int, ::AbstractReflectiveOptic, ::AbstractReflectiveOptic) + exiting_int.coincident_object = object(entering_int) + return exiting_int end -""" - interact3d(AbstractReflectiveOptic, PolarizedRay) - -Implements the ideal reflection of a [`PolarizedRay`](@ref) via the normal at the intersection point on an optical surface. -A Jones matrix of [-1 0 0; 0 1 0] is assumed as per Peatross (2015, 2023 Ed. p. 154) and Yun et al. (see [`PolarizedRay`](@ref) for more information). -""" -function interact3d(::AbstractSystem, - obj::AbstractReflectiveOptic, - ::Beam{T, R}, - ray::R) where {T <: Real, R <: PolarizedRay{T}} - normal = normal3d(intersection(ray)) - npos = position(ray) + length(ray) * direction(ray) - ndir = reflection3d(direction(ray), normal) - # Jones reflection matrix - J = SPBasis(-1, 0, 0, 1) - E0 = _calculate_global_E0(obj, ray, ndir, J) - return BeamInteraction{T, R}(nothing, - PolarizedRay{T}( - npos, ndir, nothing, wavelength(ray), refractive_index(ray), E0)) +@inline _interact_reflective_optic(::Absorptive, system, optic, coating, beam, ray) = nothing +@inline _interact_reflective_optic(::Reflective, system, optic, coating, beam, ray) = + interact_reflective_boundary(system, optic, coating, beam, ray) +@inline _interact_reflective_optic(::CoatingBehavior, system, optic, coating, beam, ray) = + is_coated(coating) ? interact_refractive_boundary(system, optic, coating, beam, ray) : interact_reflective_boundary(system, optic, coating, beam, ray) + +function interact3d(system::AbstractSystem, + optic::AbstractReflectiveOptic, + beam::Beam{T, R}, + ray::R) where {T <: Real, R <: AbstractRay{T}} + coated_obj, coating = resolve_coated_boundary(system, optic, ray) + target_obj = isnothing(coated_obj) ? optic : coated_obj + behavior = coating_behavior(coating, ray) + return _interact_reflective_optic(behavior, system, target_obj, coating, beam, ray) end """ @@ -76,8 +71,12 @@ Concrete implementation of a perfect mirror (R = 1) with arbitrary shape. !!! warning "Reflecting surfaces" It is important to consider that **all** surfaces of this mirror type are reflecting! """ -struct Mirror{T, S <: AbstractShape{T}} <: AbstractReflectiveOptic{T} +struct Mirror{T, S <: AbstractShape{T}, C <: Tuple} <: AbstractReflectiveOptic{T} shape::S + coatings::C + function Mirror(shape::S, coatings::C = ()) where {T <: Real, S <: AbstractShape{T}, C <: Tuple} + return new{T, S, C}(shape, coatings) + end end """ @@ -90,8 +89,9 @@ The reflecting surface is normal to the y-axis. - `edge_length`: the edge length of the square mirror in [m] """ -function SquarePlanoMirror2D(size::T) where {T <: Real} - shape = QuadraticFlatMesh(size) +function SquarePlanoMirror2D(size::Real) + T = float(typeof(size)) + shape = QuadraticFlatMesh(T(size)) return Mirror(shape) end @@ -103,16 +103,17 @@ The front reflecting surface is normal to the y-axis and lies at the origin. # Inputs -- `width`: of the mirror in x-direction [m] -- `height`: of the mirror in z-direction [m] -- `thickness`: of the mirror in y-direction [m] +- `width`: of the mirror in x-direction [m] +- `height`: of the mirror in z-direction [m] +- `thickness`: of the mirror in y-direction [m] """ -function RectangularPlanoMirror(width::W, height::H, thickness::T) where {W<:Real,H<:Real,T<:Real} - shape = CuboidMesh(width, thickness, height) +function RectangularPlanoMirror(width::Real, height::Real, thickness::Real) + T = float(promote_type(typeof(width), typeof(height), typeof(thickness))) + shape = CuboidMesh(T(width), T(thickness), T(height)) translate3d!(shape, [ - -width/2, # x - 0, # y - -height/2, # z + -T(width) / 2, # x + T(0), # y + -T(height) / 2 # z ]) set_new_origin3d!(shape) return Mirror(shape) @@ -130,7 +131,7 @@ See also [`RectangularPlanoMirror`](@ref). - `width`: the side length of the square mirror in x- and y-direction [m] - `thickness`: of the mirror in [m] """ -function SquarePlanoMirror(width::W, thickness::T) where {W<:Real,T<:Real} +function SquarePlanoMirror(width::Real, thickness::Real) return RectangularPlanoMirror(width, width, thickness) end @@ -158,13 +159,15 @@ Returns a cylindrical, flat [`RoundPlanoMirror`](@ref) with perfect reflectivity - `diameter`: mirror diameter in [m] - `thickness`: mirror substrate thickness in [m] """ -function RoundPlanoMirror(diameter::D, thickness::T) where {D<:Real,T<:Real} - shape = PlanoSurfaceSDF(thickness, diameter) +function RoundPlanoMirror(diameter::Real, thickness::Real) + T = float(promote_type(typeof(diameter), typeof(thickness))) + shape = PlanoSurfaceSDF(T(thickness), T(diameter)) return RoundPlanoMirror(shape) end """[`ConcaveSphericalMirror`](@ref) shape type based on a [`UnionSDF`](@ref)""" -const ConcaveSphericalMirrorShape{T} = UnionSDF{T, Tuple{ConcaveSphericalSurfaceSDF{T}, PlanoSurfaceSDF{T}}} +const ConcaveSphericalMirrorShape{T} = UnionSDF{ + T, Tuple{ConcaveSphericalSurfaceSDF{T}, PlanoSurfaceSDF{T}}} """ ConcaveSphericalMirror <: AbstractReflectiveOptic @@ -184,7 +187,7 @@ end ConcaveSphericalMirror(radius, thickness, diameter) Constructor for a spherical mirror with a concave reflecting surface. The component is aligned with the positive y-axis. -See also [`ConcaveSphericalMirror`](@ref). +See also [`ConcaveSphericalMirror`](@ref). # Inputs @@ -193,8 +196,9 @@ See also [`ConcaveSphericalMirror`](@ref). - `diameter`: mirror outer diameter in [m] """ function ConcaveSphericalMirror(radius::Real, thickness::Real, diameter::Real) - cylinder = PlanoSurfaceSDF(thickness, diameter) - concave = ConcaveSphericalSurfaceSDF(abs(radius), diameter) + T = float(promote_type(typeof(radius), typeof(thickness), typeof(diameter))) + cylinder = PlanoSurfaceSDF(T(thickness), T(diameter)) + concave = ConcaveSphericalSurfaceSDF(abs(T(radius)), T(diameter)) shape = concave + cylinder return ConcaveSphericalMirror(shape) end @@ -220,11 +224,12 @@ Constructs a right angle prism mirror. The primary surface is aligned with the p # Inputs -- `leg_length`: edge length in x and y in [m] +- `leg_length`: edge length in x and y in [m] - `height`: in z-axis in [m] """ function RightAnglePrismMirror(leg_length::Real, height::Real) - shape = RightAnglePrismSDF(leg_length, height) - zrotate3d!(shape, deg2rad(45+180)) + T = float(promote_type(typeof(leg_length), typeof(height))) + shape = RightAnglePrismSDF(T(leg_length), T(height)) + zrotate3d!(shape, T(deg2rad(45 + 180))) return RightAnglePrismMirror(shape) -end \ No newline at end of file +end diff --git a/src/OpticalComponents/Misc.jl b/src/OpticalComponents/Misc.jl index 016ccd246..d9c532aa3 100644 --- a/src/OpticalComponents/Misc.jl +++ b/src/OpticalComponents/Misc.jl @@ -31,19 +31,13 @@ The shape is represented by a tetrahedral [`Mesh`](@ref). - `mesh`: shape of the `Retroreflector` """ -struct Retroreflector{T} <: AbstractReflectiveOptic{T} +struct Retroreflector{T, C <: Tuple} <: AbstractReflectiveOptic{T} mesh::Mesh{T} + coatings::C + function Retroreflector(mesh::Mesh{T}, coatings::C = ()) where {T, C <: Tuple} + return new{T, C}(mesh, coatings) + end end shape(rr::Retroreflector) = rr.mesh - -""" - Retroreflector(scale) - -Spawns a [`Retroreflector`](@ref). - -# Inputs - -- `scale`: a scaling factor for the size of the retroreflector, e.g. `1e-3` for 1 mm -""" -Retroreflector(scale::Real) = Retroreflector(RetroMesh(scale)) +Retroreflector(scale::Real; coatings = ()) = Retroreflector(RetroMesh(scale), coatings) diff --git a/src/OpticalComponents/Polarizers/PolarizationFilter.jl b/src/OpticalComponents/Polarizers/PolarizationFilter.jl index 6912d4fb7..217c3c5e3 100644 --- a/src/OpticalComponents/Polarizers/PolarizationFilter.jl +++ b/src/OpticalComponents/Polarizers/PolarizationFilter.jl @@ -1,69 +1,26 @@ -""" - PolarizationFilter <: AbstractJonesPolarizer +# Polarization Filter Component +# Reuses the generic Coating system under the hood with a JonesCoating model. -Represents a zero-thickness, ideal polarization filter. """ -struct PolarizationFilter{T, S <: AbstractShape{T}} <: AbstractJonesPolarizer{T} - shape::S - JMat::GlobalJonesBasis{T} - cutoff::T -end - -function PolarizationFilter(shape::S, J::GlobalJonesBasis{TJ}, cs) where {TS, S<:AbstractShape{TS}, TJ} - return PolarizationFilter{TS,S}(shape, GlobalJonesBasis{TS}(J), TS(cs)) -end + PolarizationFilter(shape) + PolarizationFilter(edge_length) -""" - PolarizationFilter(edge_length; cutoff_strength) +Ideal linear polarizer. The device is represented by a zero-thickness +surface whose transmission axis is aligned with the local `x`-axis (transmitting local Ex) +and blocking axis with the local `z`-axis (blocking local Ez). -Spawns a thin, rectangular [`PolarizationFilter`](@ref). The `edge_length` has to be specified in [m]. -The filter is aligned with the global y-axis and transmits along the x-axis, while blocking polarization components -along the global z-axis. +Rotate the underlying shape around the y-axis to align the axes with the desired global directions. """ -function PolarizationFilter(edge_length::Real; cutoff_strength=eps()) - shape = QuadraticFlatMesh(edge_length) - # Rotate normals against pos. y-axis - zrotate3d!(shape, π) - set_new_origin3d!(shape) - return PolarizationFilter(shape, XZBasis(1, 0, 0, 0), cutoff_strength) +function PolarizationFilter(shape::AbstractShape{T}) where {T} + # Jones matrix transmitting x and blocking z + model = JonesCoating(XZBasis(1.0, 0.0, 0.0, 0.0)) + return Coating(shape, model) end -function interact3d(::AbstractSystem, - polfilter::PolarizationFilter, - ::Beam{T, R}, - ray::R) where {T <: Real, R <: PolarizedRay{T}} - npos = position(ray) + length(ray) * direction(ray) - ndir = direction(ray) - - E0 = _calculate_global_E0(polfilter, ray, ndir, polfilter.JMat) - - # Terminate blocked rays - # FIXME this needs to be reworked in the future - if norm(E0) ≈ polfilter.cutoff - return nothing - end - - return BeamInteraction{T, R}(nothing, - PolarizedRay{T}(npos, ndir, nothing, wavelength(ray), refractive_index(ray), E0)) -end - -function interact3d(system::AbstractSystem, - polfilter::PolarizationFilter, - agb::AstigmaticGaussianBeamlet{T}, - id::Int) where {T <: Real} - # Chief ray interaction (handles polarization change) - i_c = interact3d(system, polfilter, agb.c, rays(agb.c)[id]) - isnothing(i_c) && return nothing - - # Auxiliary rays only undergo geometric interaction with the filter shape. - # They hit at their own transverse locations, preserving beam width/divergence. - aux_ints = map(b -> begin - interact3d(system, polfilter.shape, b, rays(b)[id]) - end, _aux_beams(agb)) - - if any(isnothing, aux_ints) - return nothing - end - - return AstigmaticGaussianBeamletInteraction{T}(i_c, aux_ints...) +function PolarizationFilter(edge_length::Real) + T = float(typeof(edge_length)) + shape = QuadraticFlatMesh(T(edge_length)) + zrotate3d!(shape, T(π)) + set_new_origin3d!(shape) + return PolarizationFilter(shape) end diff --git a/src/OpticalComponents/Polarizers/Waveplate.jl b/src/OpticalComponents/Polarizers/Waveplate.jl new file mode 100644 index 000000000..d7f36a551 --- /dev/null +++ b/src/OpticalComponents/Polarizers/Waveplate.jl @@ -0,0 +1,209 @@ +# Waveplate Component +# Reuses the generic Coating system under the hood with a JonesCoating model. + +""" + Waveplate(shape, JMat) + Waveplate(diameter, retardance; fast_axis_angle=0.0) + Waveplate(width, height, retardance; fast_axis_angle=0.0) + Waveplate(diameter, thickness, n, retardance; fast_axis_angle=0.0) + Waveplate(width, height, thickness, n, retardance; fast_axis_angle=0.0) + +Ideal retarder/waveplate. The device is represented by a zero-thickness +surface whose fast axis is aligned with the local `x`-axis and slow axis with the local `z`-axis. + +Rotate the underlying shape around the y-axis to align the axes with the desired global directions. +""" +function Waveplate(shape::AbstractShape{T}, JMat::GlobalJonesBasis) where {T} + model = JonesCoating(GlobalJonesBasis{Complex{T}}(JMat)) + return Coating(shape, model) +end + +@inline _retardance_jones_matrix(r::Real) = XZBasis(exp(-im * r / 2), 0, 0, exp(im * r / 2)) +@inline _retardance_jones_matrix(f::Function) = λ -> _retardance_jones_matrix(f(λ)) +@inline _retardance_jones_matrix(m::GlobalJonesBasis) = m + +_waveplate_model_from_sample(::Real, f::Function) = JonesCoating(_retardance_jones_matrix(f)) +_waveplate_model_from_sample(::Any, f::Function) = JonesCoating(f) + +function Waveplate(shape::AbstractShape{T}, retardance::Real) where {T} + return Waveplate(shape, _retardance_jones_matrix(retardance)) +end + +function Waveplate(shape::AbstractShape{T}, f::Function) where {T} + model = _waveplate_model_from_sample(f(1e-6), f) + return Coating(shape, model) +end + +function Waveplate(diameter::Real, retardance::Union{Real, Function, GlobalJonesBasis}; fast_axis_angle::Real=0.0) + shape = CircularFlatMesh(diameter / 2) + yrotate3d!(shape, -fast_axis_angle) + return Waveplate(shape, retardance) +end + +function Waveplate(width::Real, height::Real, retardance::Union{Real, Function, GlobalJonesBasis}; fast_axis_angle::Real=0.0) + shape = RectangularFlatMesh(width, height) + zrotate3d!(shape, π) + set_new_origin3d!(shape) + yrotate3d!(shape, -fast_axis_angle) + return Waveplate(shape, retardance) +end + +#= +Thick/Plate Waveplate types and methods +=# + +abstract type AbstractPlateWaveplate{T, N} <: AbstractRefractiveOptic{T, N} end + +""" + RectangularPlateWaveplate{T, S, N, C} <: AbstractPlateWaveplate{T, N} + +A rectangular waveplate with a bulk glass substrate and a retarder coating on its front face. +""" +struct RectangularPlateWaveplate{T, S <: BoxSDF{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractPlateWaveplate{T, N} + shape::S + n::N + coatings::C + function RectangularPlateWaveplate( + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: BoxSDF{T}, N <: RefractiveIndex, C <: Tuple} + test_refractive_index_function(n) + return new{T, S, N, C}(shape, n, coatings) + end +end + +""" + RoundPlateWaveplate{T, S, N, C} <: AbstractPlateWaveplate{T, N} + +A round (cylindrical) waveplate with a bulk glass substrate and a retarder coating on its front face. +""" +struct RoundPlateWaveplate{T, S <: PlanoSurfaceSDF{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractPlateWaveplate{T, N} + shape::S + n::N + coatings::C + function RoundPlateWaveplate( + shape::S, n::N, coatings::C = ()) where {T <: Real, S <: PlanoSurfaceSDF{T}, N <: RefractiveIndex, C <: Tuple} + test_refractive_index_function(n) + return new{T, S, N, C}(shape, n, coatings) + end +end + +# Compatibility accessors +substrate(p::AbstractPlateWaveplate) = p +coating(p::AbstractPlateWaveplate) = get_matching_coating(coatings(p), shape(p), [0.0, 0.0, 0.0], [0.0, -1.0, 0.0]) + +function RectangularPlateWaveplate( + width::Real, + height::Real, + thickness::Real, + n::RefractiveIndex, + retardance::Union{Real, Function}; + fast_axis_angle::Real=0.0, + back_coating=nothing +) + T = float(promote_type(typeof(width), typeof(height), typeof(thickness))) + substrate_shape = BoxSDF(T(width), T(thickness), T(height)) + translate3d!(substrate_shape, [T(0), T(thickness/2), T(0)]) + if fast_axis_angle != 0.0 + yrotate3d!(substrate_shape, -T(fast_axis_angle)) + end + + coat_wp = JonesCoating(_retardance_jones_matrix(retardance)) + + coatings_list = if isnothing(back_coating) + (:front => coat_wp,) + else + (:front => coat_wp, :back => _coating_model(back_coating)) + end + + return RectangularPlateWaveplate(substrate_shape, n, coatings_list) +end + +function RoundPlateWaveplate( + diameter::Real, + thickness::Real, + n::RefractiveIndex, + retardance::Union{Real, Function}; + fast_axis_angle::Real=0.0, + back_coating=nothing +) + T = float(promote_type(typeof(diameter), typeof(thickness))) + substrate_shape = PlanoSurfaceSDF(T(thickness), T(diameter)) + if fast_axis_angle != 0.0 + yrotate3d!(substrate_shape, -T(fast_axis_angle)) + end + + coat_wp = JonesCoating(_retardance_jones_matrix(retardance)) + + coatings_list = if isnothing(back_coating) + (:front => coat_wp,) + else + (:front => coat_wp, :back => _coating_model(back_coating)) + end + + return RoundPlateWaveplate(substrate_shape, n, coatings_list) +end + +# Factory mapping to round/rectangular plate waveplates +function Waveplate(diameter::Real, thickness::Real, n::RefractiveIndex, retardance::Union{Real, Function}; fast_axis_angle::Real=0.0, back_coating=nothing) + return RoundPlateWaveplate(diameter, thickness, n, retardance; fast_axis_angle=fast_axis_angle, back_coating=back_coating) +end + +function Waveplate(width::Real, height::Real, thickness::Real, n::RefractiveIndex, retardance::Union{Real, Function}; fast_axis_angle::Real=0.0, back_coating=nothing) + return RectangularPlateWaveplate(width, height, thickness, n, retardance; fast_axis_angle=fast_axis_angle, back_coating=back_coating) +end + + +#= +Waveplate Factory/Convenience Constructors +=# + +""" + HalfWavePlate(diameter; fast_axis_angle=0.0) + HalfWavePlate(width, height; fast_axis_angle=0.0) + HalfWavePlate(diameter, thickness, n; fast_axis_angle=0.0) + HalfWavePlate(width, height, thickness, n; fast_axis_angle=0.0) + +Creates a Half-Wave Plate (retardance of π) of flat or thick, round or rectangular geometry. +""" +function HalfWavePlate(diameter::Real; fast_axis_angle::Real=0.0) + return Waveplate(diameter, π; fast_axis_angle=fast_axis_angle) +end + +function HalfWavePlate(width::Real, height::Real; fast_axis_angle::Real=0.0) + return Waveplate(width, height, π; fast_axis_angle=fast_axis_angle) +end + +function HalfWavePlate(diameter::Real, thickness::Real, n::RefractiveIndex; fast_axis_angle::Real=0.0) + return Waveplate(diameter, thickness, n, π; fast_axis_angle=fast_axis_angle) +end + +function HalfWavePlate(width::Real, height::Real, thickness::Real, n::RefractiveIndex; fast_axis_angle::Real=0.0) + return Waveplate(width, height, thickness, n, π; fast_axis_angle=fast_axis_angle) +end + +""" + QuarterWavePlate(diameter; fast_axis_angle=0.0) + QuarterWavePlate(width, height; fast_axis_angle=0.0) + QuarterWavePlate(diameter, thickness, n; fast_axis_angle=0.0) + QuarterWavePlate(width, height, thickness, n; fast_axis_angle=0.0) + +Creates a Quarter-Wave Plate (retardance of π/2) of flat or thick, round or rectangular geometry. +""" +function QuarterWavePlate(diameter::Real; fast_axis_angle::Real=0.0) + return Waveplate(diameter, π/2; fast_axis_angle=fast_axis_angle) +end + +function QuarterWavePlate(width::Real, height::Real; fast_axis_angle::Real=0.0) + return Waveplate(width, height, π/2; fast_axis_angle=fast_axis_angle) +end + +function QuarterWavePlate(diameter::Real, thickness::Real, n::RefractiveIndex; fast_axis_angle::Real=0.0) + return Waveplate(diameter, thickness, n, π/2; fast_axis_angle=fast_axis_angle) +end + +function QuarterWavePlate(width::Real, height::Real, thickness::Real, n::RefractiveIndex; fast_axis_angle::Real=0.0) + return Waveplate(width, height, thickness, n, π/2; fast_axis_angle=fast_axis_angle) +end + +# Spelling aliases for Waveplates branch compatibility +const HalfWaveplate = HalfWavePlate +const QuarterWaveplate = QuarterWavePlate diff --git a/src/OpticalComponents/Prisms.jl b/src/OpticalComponents/Prisms.jl index c2a9254b7..d481138af 100644 --- a/src/OpticalComponents/Prisms.jl +++ b/src/OpticalComponents/Prisms.jl @@ -4,12 +4,13 @@ Essentially represents the same functionality as [`Lens`](@ref). Refer to its documentation. """ -struct Prism{T, S <: AbstractShape{T}, N <: RefractiveIndex} <: AbstractRefractiveOptic{T, N} +struct Prism{T, S <: AbstractShape{T}, N <: RefractiveIndex, C <: Tuple} <: AbstractRefractiveOptic{T, N} shape::S n::N - function Prism(shape::S, n::N) where {T<:Real, S<:AbstractShape{T}, N<:RefractiveIndex} + coatings::C + function Prism(shape::S, n::N, coatings::C = ()) where {T <: Real, S <: AbstractShape{T}, N <: RefractiveIndex, C <: Tuple} test_refractive_index_function(n) - return new{T, S, N}(shape, n) + return new{T, S, N, C}(shape, n, coatings) end end diff --git a/src/Workloads/coatings_wl.jl b/src/Workloads/coatings_wl.jl new file mode 100644 index 000000000..e81752465 --- /dev/null +++ b/src/Workloads/coatings_wl.jl @@ -0,0 +1,28 @@ +@setup_workload begin + λ = 1000e-9 + @compile_workload begin + nc = sqrt(1.5) + d = λ / (4 * nc) + coat_thin = ThinFilmCoating(nc, d; behavior = Transmissive()) + + n_lens = λ -> 1.5 + base_lens = SphericalLens(100e-3, -100e-3, 5e-3, 10e-3, n_lens) + coated_lens = base_lens |> with_coatings(front = coat_thin) + + system = System([coated_lens]) + + # Trace plain Ray + ray_lr = Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam_lr = Beam(ray_lr) + solve_system!(system, beam_lr; retrace = false) + + # Trace PolarizedRay + pray = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) + pbeam = Beam(pray) + solve_system!(system, pbeam; retrace = false) + + # Trace GaussianBeamlet + gauss = GaussianBeamlet([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, 1e-3) + solve_system!(system, gauss; retrace = false) + end +end diff --git a/src/Workloads/precompile.jl b/src/Workloads/precompile.jl index 5226a3013..93625831c 100644 --- a/src/Workloads/precompile.jl +++ b/src/Workloads/precompile.jl @@ -3,5 +3,6 @@ if get(ENV, "CI", "false") == "false" let include("michelson_wl.jl") include("asphere_wl.jl") + include("coatings_wl.jl") end end \ No newline at end of file diff --git a/test/Components/TestBeamsplitters.jl b/test/Components/TestBeamsplitters.jl index 29ad78fff..878915e26 100644 --- a/test/Components/TestBeamsplitters.jl +++ b/test/Components/TestBeamsplitters.jl @@ -9,6 +9,21 @@ const mm = 1e-3 @testset "Beamsplitters" begin N0 = 1.5 + + @testset "PlateBeamsplitter Constructor Type Promotion" begin + # Passing integer dimensions to RectangularPlateBeamsplitter + rpbs = RectangularPlateBeamsplitter(36, 25, 1, n -> N0) + @test rpbs isa RectangularPlateBeamsplitter{Float64} + @test BMO.shape(rpbs) isa BMO.BoxSDF{Float64} + @test BMO.coatings(rpbs)[1].second isa BMO.SimpleBeamsplitterCoating + + # Passing integer dimensions to RoundPlateBeamsplitter + round_pbs = RoundPlateBeamsplitter(25, 1, n -> N0) + @test round_pbs isa RoundPlateBeamsplitter{Float64} + @test BMO.shape(round_pbs) isa BMO.PlanoSurfaceSDF{Float64} + @test BMO.coatings(round_pbs)[1].second isa BMO.SimpleBeamsplitterCoating + end + @testset "Testing RectangularPlateBeamsplitter with Beam" begin # Init splitter N0 = 1.5 @@ -20,8 +35,7 @@ const mm = 1e-3 solve_system!(system, beam) @testset "Test pos/dir" begin - @test position(pbs) == zeros(3) - @test orientation(pbs) ≈ orientation(pbs.substrate) + @test orientation(pbs) ≈ orientation(BMO.shape(pbs)) end @testset "Test children after tracing" begin @@ -61,6 +75,14 @@ const mm = 1e-3 @test BMO.direction(first(p)) ≈ BMO.direction(last(t)) @test BMO.direction(last(r)) ≈ [1, 0, 0] end + + @testset "PlateBeamsplitter with AR back_coating" begin + pbs_ar = RectangularPlateBeamsplitter(36mm, 25mm, 1mm, n -> N0; back_coating=SimpleARCoating()) + @test length(BMO.coatings(pbs_ar)) == 2 + @test BMO.coatings(pbs_ar)[1].first == :front + @test BMO.coatings(pbs_ar)[2].first == :back + @test BMO.coatings(pbs_ar)[2].second isa SimpleARCoating + end end @testset "Testing CubeBeamsplitter with Beam" begin diff --git a/test/Components/TestBulkAbsorption.jl b/test/Components/TestBulkAbsorption.jl new file mode 100644 index 000000000..88b5f037f --- /dev/null +++ b/test/Components/TestBulkAbsorption.jl @@ -0,0 +1,150 @@ +using Test +using BeamletOptics +using LinearAlgebra +const BMO = BeamletOptics + +@testset "Bulk Absorption and Small-Signal Gain" begin + λ = 1000e-9 # 1 μm + + @testset "AbsorbingMedium & GainMedium Functors" begin + # AbsorbingMedium with constant α + α0 = 100.0 # 100 1/m (1/cm) + med_abs = AbsorbingMedium(1.5, α0) + n_c = med_abs(λ) + @test real_refractive_index(n_c) ≈ 1.5 + expected_κ = (α0 * λ) / (4π) + @test extinction_coefficient(n_c) ≈ expected_κ + @test absorption_coefficient(n_c, λ) ≈ α0 + + # GainMedium with constant g + g0 = 50.0 # 50 1/m + med_gain = GainMedium(1.8, g0) + n_gain = med_gain(λ) + @test real_refractive_index(n_gain) ≈ 1.8 + expected_gain_κ = -(g0 * λ) / (4π) + @test extinction_coefficient(n_gain) ≈ expected_gain_κ + @test absorption_coefficient(n_gain, λ) ≈ -g0 + + # bulk_attenuation_factor helper + L = 0.01 # 10 mm + att_p, att_f = bulk_attenuation_factor(n_c, λ, L) + @test att_p ≈ exp(-α0 * L) + @test att_f ≈ exp(-α0 * L / 2) + + att_gain_p, att_gain_f = bulk_attenuation_factor(n_gain, λ, L) + @test att_gain_p ≈ exp(g0 * L) + @test att_gain_f ≈ exp(g0 * L / 2) + + # Non-absorbing medium + att_real_p, att_real_f = bulk_attenuation_factor(1.5, λ, L) + @test att_real_p ≈ 1.0 + @test att_real_f ≈ 1.0 + end + + @testset "Ray Lambert-Beer Attenuation through Planar Slab" begin + d = 10e-3 # 10 mm thickness + α = 200.0 # 200 1/m + med = AbsorbingMedium(1.5, α) + + # Flat plano-planar lens with AR coatings to isolate bulk attenuation + slab = SphericalLens(Inf, Inf, d, 20e-3, med) |> with_coatings( + front = SimpleARCoating(0.0), + back = SimpleARCoating(0.0) + ) + sys = System([slab]) + + ray = Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam = Beam(ray) + solve_system!(sys, beam; retrace = false) + + # Ray 1: before slab, Ray 2: inside slab, Ray 3: after slab + ray_inside = rays(beam)[2] + ray_exit = rays(beam)[3] + + @test length(ray_inside) ≈ d + @test ray_inside.weight ≈ 1.0 # Enters without loss due to AR coating + # Exiting ray should be attenuated by Lambert-Beer factor exp(-α * d) + @test ray_exit.weight ≈ exp(-α * d) + end + + @testset "PolarizedRay Bulk Attenuation with Fresnel Interfaces" begin + d = 5e-3 # 5 mm thickness + α = 150.0 # 150 1/m + med = AbsorbingMedium(1.5, α) + + # Uncoated plano-planar slab (Fresnel reflections at both interfaces) + slab_uncoated = SphericalLens(Inf, Inf, d, 20e-3, med) + sys = System([slab_uncoated]) + + E0_init = [1.0, 0.0, 0.0] + ray_pol = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, E0_init) + beam_pol = Beam(ray_pol) + solve_system!(sys, beam_pol; retrace = false) + + ray_inside = rays(beam_pol)[2] + ray_exit = rays(beam_pol)[3] + + # Exact complex Fresnel transmission: + n_c = med(λ) + _, _, ts1, _ = BMO.fresnel_coefficients(0.0, n_c / 1.0) + _, _, ts2, _ = BMO.fresnel_coefficients(0.0, 1.0 / n_c) + expected_E = abs(ts1 * exp(-α * d / 2) * ts2) + E_exit = abs(BMO.polarization(ray_exit)[1]) + @test E_exit ≈ expected_E + end + + @testset "Laser Gain Medium (Small-Signal Gain)" begin + d = 20e-3 # 20 mm crystal length + g = 80.0 # 80 1/m gain + crystal = SphericalLens(Inf, Inf, d, 10e-3, GainMedium(1.82, g)) |> with_coatings( + front = SimpleARCoating(0.0), + back = SimpleARCoating(0.0) + ) + sys = System([crystal]) + + ray = Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam = Beam(ray) + solve_system!(sys, beam; retrace = false) + + ray_exit = rays(beam)[3] + @test ray_exit.weight ≈ exp(g * d) + end + + @testset "Direct Complex Refractive Index Function" begin + # Passing an anonymous function returning Complex directly: λ -> 1.6 + 0.0005im + n_func = λ -> complex(1.6, 5e-4) + α_calc = 4π * 5e-4 / λ + d = 10e-3 + slab = SphericalLens(Inf, Inf, d, 20e-3, n_func) |> with_coatings( + front = SimpleARCoating(0.0), + back = SimpleARCoating(0.0) + ) + sys = System([slab]) + + ray = Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam = Beam(ray) + solve_system!(sys, beam; retrace = false) + + ray_exit = rays(beam)[3] + @test ray_exit.weight ≈ exp(-α_calc * d) + end + + @testset "Detector Hit Recording inside Absorbing Medium" begin + d = 10e-3 + α = 100.0 + # Ray travelling in absorbing medium hitting a detector + det = Detector(10e-3) + translate3d!(det, [0.0, d, 0.0]) + + sys = System([det]) + # Start ray with complex n + n_c = complex(1.5, (α * λ) / (4π)) + ray = Ray([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], λ) + ray.n = n_c + beam = Beam(ray) + solve_system!(sys, beam; retrace = false) + + hit = BMO.hits(det)[1] + @test hit.ray.weight ≈ exp(-α * d) + end +end diff --git a/test/Components/TestCoatings.jl b/test/Components/TestCoatings.jl new file mode 100644 index 000000000..b1c65f619 --- /dev/null +++ b/test/Components/TestCoatings.jl @@ -0,0 +1,864 @@ +using Test +using BeamletOptics +using LinearAlgebra +const BMO = BeamletOptics + +@testset "Coatings and Coated Components" begin + # Test Uncoated coefficients + rs_unc, rp_unc, ts_unc, tp_unc = BMO.fresnel_coefficients( + Uncoated(), 0.0, 1000e-9, 1.0, 1.5) + @test rs_unc ≈ -0.2 + @test rp_unc ≈ -0.2 + @test ts_unc ≈ 0.8 + @test tp_unc ≈ 0.8 + + # Test get_jones_matrix for Uncoated + J_refl = get_jones_matrix(Uncoated(), 0.0, 1000e-9, 1.0, 1.5, true) + J_trans = get_jones_matrix(Uncoated(), 0.0, 1000e-9, 1.0, 1.5, false) + @test J_refl[1, 1] ≈ 0.2 + @test J_refl[2, 2] ≈ -0.2 + @test J_trans[1, 1] ≈ 0.8 + @test J_trans[2, 2] ≈ 0.8 + + # Test quarter-wave AR coating at normal incidence + # n1 = 1.0, n2 = 1.5. Optimal nc = sqrt(1.5). + # d = lambda / (4 * nc) + λ = 1000e-9 + nc = sqrt(1.5) + d = λ / (4 * nc) + coat_thin = ThinFilmCoating(nc, d) + + rs, rp, ts, tp = BMO.fresnel_coefficients(coat_thin, 0.0, λ, 1.0, 1.5) + @test abs(rs) < 1e-12 + @test abs(rp) < 1e-12 + @test abs(ts) ≈ sqrt(1.0 / 1.5) # Power transmission is 100%, amplitude ratio is sqrt(n1/n2) + @test abs(tp) ≈ sqrt(1.0 / 1.5) + + # Test Lens Interaction with Coating (Bidirectional & Custom Filters) + n_lens = λ -> 1.5 + base_lens = SphericalLens(100e-3, -100e-3, 5e-3, 10e-3, n_lens) + coated_lens = base_lens |> with_coatings(front = coat_thin) + + system = System([coated_lens]) + + # Trace left-to-right (enters coated front, exits uncoated back) + ray_lr = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) + beam_lr = Beam(ray_lr) + solve_system!(system, beam_lr; retrace = false) + + # Ray 1: before lens, Ray 2: inside (AR coated), Ray 3: outside (uncoated exit) + ray_inside_lr = rays(beam_lr)[2] + @test ray_inside_lr.n ≈ 1.5 + @test abs(BMO.polarization(ray_inside_lr)[1]) ≈ sqrt(1.0 / 1.5) + + ray_exit_lr = rays(beam_lr)[3] + @test ray_exit_lr.n ≈ 1.0 + # Inside polarization is sqrt(1/1.5). Uncoated exit: multiplied by 2 * 1.5 / (1.5 + 1.0) = 1.2. + @test abs(BMO.polarization(ray_exit_lr)[1]) ≈ sqrt(1.0 / 1.5) * 1.2 + + # Trace right-to-left (enters uncoated back, exits coated front) + ray_rl = PolarizedRay([0.0, 10e-3, 0.0], [0.0, -1.0, 0.0], λ, [1.0, 0.0, 0.0]) + beam_rl = Beam(ray_rl) + solve_system!(system, beam_rl; retrace = false) + + # Ray 1: before lens, Ray 2: inside (uncoated entry), Ray 3: outside (AR coated exit) + ray_inside_rl = rays(beam_rl)[2] + @test ray_inside_rl.n ≈ 1.5 + # Uncoated entry: multiplied by 2 * 1.0 / (1.0 + 1.5) = 0.8 + @test abs(BMO.polarization(ray_inside_rl)[1]) ≈ 0.8 + + ray_exit_rl = rays(beam_rl)[3] + @test ray_exit_rl.n ≈ 1.0 + # AR coated exit: transmittance is 1.0, amplitude ratio factor is sqrt(1.5 / 1.0). + @test abs(BMO.polarization(ray_exit_rl)[1]) ≈ 0.8 * sqrt(1.5) + + # Test custom normal filter construction + coating_custom = Coating( + BMO.shape(base_lens), coat_thin, normal_filter = [0.0, -1.0, 0.0]) + @test coating_custom.normal_filter ≈ [0.0, -1.0, 0.0] + + # Test Mirror Interaction with Coating + # Coat a flat mirror with a SimpleHRCoating (reflectance = 99%) + mirror_base = SquarePlanoMirror2D(10e-3) + coated_mirror = mirror_base |> with_coatings(front = SimpleHRCoating(0.99)) + + system_mirror = System([coated_mirror]) + ray_mirror = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) + beam_mirror = Beam(ray_mirror) + solve_system!(system_mirror, beam_mirror; retrace = false) + + ray_reflected = rays(beam_mirror)[2] + @test abs(BMO.polarization(ray_reflected)[1]) ≈ sqrt(0.99) + + # Test Waveplate Coating + # Construct a JonesCoating representing a quarter-wave plate (retardation pi/2 along fast axis) + # Global Jones Basis for XZBasis: Ex is fast axis (retardation 0), Ez is slow axis (retardation pi/2) + wp_jones = BMO.XZBasis(1.0, 0.0, 0.0, exp(im * π / 2)) + coat_wp = JonesCoating(wp_jones, BMO.XZBasis(0, 0, 0, 0)) + + # Plano-planar lens of index 1.0 (air) coated on its front surface + n_air = λ -> 1.0 + base_planar = SphericalLens(Inf, Inf, 1e-3, 10e-3, n_air) + coated_planar = base_planar |> with_coatings(front = coat_wp) + + system_wp = System([coated_planar]) + # Trace a linearly polarized ray with equal components in Ex and Ez (45 degrees) + ray_wp = PolarizedRay( + [0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], λ, [1 / sqrt(2), 0.0, 1 / sqrt(2)]) + beam_wp = Beam(ray_wp) + solve_system!(system_wp, beam_wp; retrace = false) + + ray_out = rays(beam_wp)[2] # after first surface + pol_out = BMO.polarization(ray_out) + @test pol_out[1] ≈ 1 / sqrt(2) + @test pol_out[3] ≈ im / sqrt(2) + + # Test Coated Cube Beamsplitter + # Custom coating on the splitter interface (transmittance 80%, reflectance 20%) + coat_bs = SimpleBeamsplitterCoating(sqrt(0.2), sqrt(0.2), sqrt(0.8), sqrt(0.8)) + + flat_mesh = BMO.QuadraticFlatMesh(10e-3) + coating_obj = Coating(flat_mesh, coat_bs) + + system_bs = System([coating_obj]) + ray_bs = PolarizedRay([0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) + beam_bs = Beam(ray_bs) + solve_system!(system_bs, beam_bs; retrace = false) + + # We should have child 1 (transmitted) and child 2 (reflected) from the splitter + @test length(beam_bs.children) == 2 + ray_t = first(rays(beam_bs.children[1])) + @test abs(BMO.polarization(ray_t)[1]) ≈ sqrt(0.8) + + ray_r = first(rays(beam_bs.children[2])) + @test abs(BMO.polarization(ray_r)[1]) ≈ sqrt(0.2) + + # Test Coated Doublet Lens (Cemented Coating) + n1_doublet = λ -> 1.5 + n2_doublet = λ -> 1.6 + + dl_front = SphericalLens(Inf, -100e-3, 5e-3, 10e-3, n1_doublet) + dl_back = SphericalLens(-100e-3, Inf, 5e-3, 10e-3, n2_doublet) + + # Coat the cemented boundary between dl_front and dl_back + coat_cement = SimpleARCoating(0.01) # 1% reflectance + + dl_front_coated = with_coatings(dl_front, back = coat_cement) + + # Move back lens flush with front lens + translate3d!(dl_back, [0, thickness(dl_front), 0]) + + system_dl = System([dl_front_coated, dl_back]) + ray_dl = PolarizedRay([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], λ, [1.0, 0.0, 0.0]) + beam_dl = Beam(ray_dl) + solve_system!(system_dl, beam_dl; retrace = false) + + # Verify index and polarization amplitude scaling at cemented interface + @test length(rays(beam_dl)) >= 3 + ray_inside_back = rays(beam_dl)[3] + @test ray_inside_back.n ≈ 1.6 + + pol_inside_back = BMO.polarization(ray_inside_back) + @test abs(pol_inside_back[1]) ≈ 0.8 * sqrt(0.99) + + # Test Segmented Coating (Spatial Predicates) + # Lens with left-half AR coated, right-half HR coated + left_half = (p, n) -> p[1] < 0.0 + right_half = (p, n) -> p[1] >= 0.0 + + ar_model = SimpleARCoating(0.0) + hr_model = SimpleHRCoating(1.0) + + base_lens_flat = SphericalLens(Inf, Inf, 1e-3, 10e-3, n_air) + coated_segmented = with_coatings( + base_lens_flat, + left_half => ar_model, + right_half => hr_model + ) + + system_seg = System([coated_segmented]) + + # Ray 1: hits left half (transmissive segment) + ray_seg_l = Ray([-2e-3, -5e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam_seg_l = Beam(ray_seg_l) + solve_system!(system_seg, beam_seg_l; retrace = false) + # Should transmit through: pos after lens is around y = 0.005 + @test length(rays(beam_seg_l)) == 3 + @test rays(beam_seg_l)[3].pos[2] > 0.0 + + # Ray 2: hits right half (reflective segment) + ray_seg_r = Ray([2e-3, -5e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam_seg_r = Beam(ray_seg_r) + solve_system!(system_seg, beam_seg_r; retrace = false) + # Should reflect back: direction is [0.0, -1.0, 0.0] + @test length(rays(beam_seg_r)) == 2 + @test rays(beam_seg_r)[2].dir[2] ≈ -1.0 + + # Test Face-Selective Coating on a Right Angle Prism + n_prism = λ -> 1.5 + prism_base = RightAnglePrism(10e-3, 10e-3, n_prism) + # Coat the hypotenuse with HR, keep other legs uncoated + coated_prism = with_coatings(prism_base, :hypotenuse => hr_model) + + system_prism = System([coated_prism]) + # Send a ray entering from Leg 2 (y=-5e-3), hitting hypotenuse (x+y=0), reflecting out of Leg 1 (x=-5e-3) + ray_prism = Ray([-2e-3, -10e-3, 0.0], [0.0, 1.0, 0.0], λ) + beam_prism = Beam(ray_prism) + solve_system!(system_prism, beam_prism; retrace = false) + + # Ray 1: before prism (starts at y=-10e-3) + # Ray 2: inside prism (enters y=-5e-3, goes to y=2e-3) + # Ray 3: inside prism (reflects to [-1, 0, 0], goes to x=-5e-3) + # Ray 4: after prism (exits Leg 1, goes to x < -5e-3) + @test length(rays(beam_prism)) == 4 + @test rays(beam_prism)[3].dir[1] ≈ -1.0 + @test rays(beam_prism)[4].dir[1] ≈ -1.0 + + @testset "Phase Convention Validation" begin + # Let's define a plano-planar lens of glass (n = 1.5) + n_glass = λ -> 1.5 + planar_lens = SphericalLens(Inf, Inf, 1e-3, 10e-3, n_glass) + + # Splitting coating (bare index jump splitting) + splitting_coating = ThinFilmCoating( + Float64[], Float64[]; behavior = BMO.Splitting()) + + # External Normal Reflection (Air to Glass) + coated_lens_ext = with_coatings(planar_lens, front = splitting_coating) + system_ext = System([coated_lens_ext]) + + gauss_ext = GaussianBeamlet([0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1e-3) + solve_system!(system_ext, gauss_ext; retrace = false) + + @test length(gauss_ext.children) == 2 + t_ext = gauss_ext.children[1] + r_ext = gauss_ext.children[2] + @test electric_field(r_ext) / electric_field(gauss_ext)≈-0.2 atol=1e-8 + + # Internal Normal Reflection (Glass to Air) + coated_lens_int = with_coatings(planar_lens, back = splitting_coating) + system_int = System([coated_lens_int]) + + gauss_int = GaussianBeamlet([0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1e-3) + solve_system!(system_int, gauss_int; retrace = false) + + @test length(gauss_int.children) == 2 + t_int = gauss_int.children[1] + r_int = gauss_int.children[2] + @test electric_field(r_int) / electric_field(gauss_int)≈0.2 atol=1e-8 + + # Consistency of Polarization and Amplitude for AstigmaticGaussianBeamlet + p_ray_ext = PolarizedRay( + [0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9, [1.0, 0.0, 0.0]) + p_beam = Beam(p_ray_ext) + solve_system!(system_ext, p_beam; retrace = false) + + @test length(p_beam.children) == 2 + p_r = first(rays(p_beam.children[2])) + + agb_ext = AstigmaticGaussianBeamlet( + [0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1e-3; + E0 = [1.0, 0.0, 0.0], support = [0.0, 0.0, 1.0]) + solve_system!(system_ext, agb_ext; retrace = false) + + @test length(agb_ext.children) == 2 + agb_r = agb_ext.children[2] + agb_r_chief = first(rays(agb_r.c)) + @test agb_r_chief.E0≈p_r.E0 atol=1e-8 + end + + @testset "Complex Refractive Index ThinFilmCoating" begin + # Test a thin metallic coating (e.g. chromium: n = 3.0 + 4.0im) + λ = 1000e-9 + n_metal = 3.0 + 4.0im + d_metal = 10e-9 # 10 nm physical thickness + coat_metal = ThinFilmCoating(n_metal, d_metal; behavior = BMO.Reflective()) + + rs, rp, ts, tp = BMO.fresnel_coefficients(coat_metal, 0.0, λ, 1.0, 1.5) + # Verify coefficients are complex numbers + @test rs isa Complex + @test rp isa Complex + @test ts isa Complex + @test tp isa Complex + # Non-zero reflection/transmission due to finite thickness + @test abs(rs) > 0.0 + @test abs(ts) > 0.0 + end + + @testset "TIR on Splitting Boundaries" begin + # Plano-planar lens (n = 1.5) with back surface coated with splitting coating + n_glass = λ -> 1.5 + planar_lens = SphericalLens(Inf, Inf, 1e-3, 10e-3, n_glass) + splitting_coating = ThinFilmCoating( + Float64[], Float64[]; behavior = BMO.Splitting()) + coated_lens = with_coatings(planar_lens, back = splitting_coating) + system = System([coated_lens]) + + # Single Ray starting inside the glass lens heading towards the back surface at 45 degrees + # Normal to back surface is [0.0, 1.0, 0.0] + # Ray direction: normalize([1.0, 1.0, 0.0]), which has 45 deg angle of incidence + dir_45 = normalize([1.0, 1.0, 0.0]) + ray = Ray{Float64}([0.0, -0.4e-3, 0.0], dir_45, nothing, 1000e-9, 1.5) + beam = Beam(ray) + solve_system!(system, beam; retrace = false) + + # Under TIR, the ray should reflect (direction [1/√2, -1/√2, 0.0]) and stay in glass (n=1.5) + # Then it hits the front surface (normal [0.0, -1.0, 0.0]) and exits into air. + @test length(rays(beam)) >= 3 + refl_ray = rays(beam)[3] + @test refl_ray.dir[1] ≈ 1 / sqrt(2) + @test refl_ray.dir[2] ≈ -1 / sqrt(2) + @test refl_ray.n ≈ 1.5 + @test isempty(beam.children) # No children created! + + # Polarized Ray starting inside the glass lens + pray = PolarizedRay{Float64}( + [0.0, -0.4e-3, 0.0], dir_45, nothing, 1000e-9, 1.5, [0.0, 0.0, 1.0]) + pbeam = Beam(pray) + solve_system!(system, pbeam; retrace = false) + @test length(rays(pbeam)) >= 3 + refl_pray = rays(pbeam)[3] + @test refl_pray.dir[1] ≈ 1 / sqrt(2) + @test refl_pray.dir[2] ≈ -1 / sqrt(2) + @test refl_pray.n ≈ 1.5 + @test isempty(pbeam.children) + + # Gaussian Beamlet starting inside the glass lens + chief_ray = Ray{Float64}([0.0, -0.4e-3, 0.0], dir_45, nothing, 1000e-9, 1.5) + waist_ray = Ray{Float64}([0.0, -0.4e-3, 0.1e-3], dir_45, nothing, 1000e-9, 1.5) + div_ray = Ray{Float64}( + [0.0, -0.4e-3, 0.0], normalize([1.0, 1.0, 0.01]), nothing, 1000e-9, 1.5) + chief_beam = Beam(chief_ray) + waist_beam = Beam(waist_ray) + div_beam = Beam(div_ray) + gauss = GaussianBeamlet( + chief_beam, waist_beam, div_beam, 1000e-9, 1e-3, 1.0 + 0.0im) + solve_system!(system, gauss; retrace = false) + @test isempty(gauss.children) # Should not split under TIR! + end + + @testset "Frustrated Total Internal Reflection (FTIR) on Splitting Boundaries" begin + # Glass index n=1.5 + n_glass = λ -> 1.5 + + # 100 nm air gap splitting coating (index 1.0, thickness 100nm) + ftir_coating = ThinFilmCoating(1.0, 100e-9; behavior = BMO.Splitting()) + + # Two plano-planar lenses made of glass + lens_front = SphericalLens(Inf, Inf, 1e-3, 10e-3, n_glass) + lens_back = SphericalLens(Inf, Inf, 1e-3, 10e-3, n_glass) + + # Coat the back of the front lens with our air gap coating + dl_front_coated = with_coatings(lens_front; back = ftir_coating) + + # Place the back lens right after the front lens (thickness is 1mm) + translate3d!(lens_back, [0.0, 1e-3, 0.0]) + + system = System([dl_front_coated, lens_back]) + + # Launch a ray inside the front lens hitting the coated boundary at 45 degrees + # (Incident angle 45 deg > critical angle 41.8 deg, but because the transmitted + # medium is also glass (n=1.5), it does not trigger the bulk TIR check). + dir_45 = normalize([1.0, 1.0, 0.0]) + ray = Ray{Float64}([0.0, -0.4e-3, 0.0], dir_45, nothing, 1000e-9, 1.5) + beam = Beam(ray) + + solve_system!(system, beam; retrace = false, depth_max = 1) + + # Verify that FTIR allows both reflection and transmission (splitting happens) + @test length(beam.children) == 2 + + t_child = beam.children[1] + r_child = beam.children[2] + + @test length(BMO.rays(t_child)) >= 1 + @test length(BMO.rays(r_child)) >= 1 + + t_ray = first(BMO.rays(t_child)) + r_ray = first(BMO.rays(r_child)) + + # Verify weight/power distribution. T and R should be non-zero and sum to ~1. + # Since T is non-zero, evanescent coupling/frustration is working. + T_weight = BMO.weight(t_ray) + R_weight = BMO.weight(r_ray) + @test T_weight > 0.0 + @test R_weight > 0.0 + @test T_weight + R_weight≈1.0 atol=1e-5 + end + + @testset "Backwards Ray Coincident Boundary Bug" begin + # Issue: Rays tracing backwards through a coincident coated boundary + # had flipped refractive indices because of `isentering` relying on intersection primary object. + n1_doublet = λ -> 1.5 + n2_doublet = λ -> 1.6 + + dl_front = SphericalLens(Inf, -100e-3, 5e-3, 10e-3, n1_doublet) + dl_back = SphericalLens(-100e-3, Inf, 5e-3, 10e-3, n2_doublet) + + coat_cement = SimpleARCoating(0.01) + dl_front_coated = with_coatings(dl_front; back = coat_cement) + + translate3d!(dl_back, [0, thickness(dl_front), 0]) + + # Reverse order to ensure dl_back is the primary coincident object + system_rev = System([dl_back, dl_front_coated]) + + # Ray starts behind the back lens and travels backwards + ray_bwd = PolarizedRay( + [0.0, 12e-3, 0.0], [0.0, -1.0, 0.0], 1000e-9, [1.0, 0.0, 0.0]) + beam_bwd = Beam(ray_bwd) + solve_system!(system_rev, beam_bwd; retrace = false) + + @test length(rays(beam_bwd)) >= 3 + # Ray 1: Air to dl_back (y=12e-3 to 10e-3) + # Ray 2: Inside dl_back (y=10e-3 to 5e-3) + # Ray 3: Inside dl_front (y=5e-3 to 0.0) + + r2 = rays(beam_bwd)[2] + @test r2.n ≈ 1.6 + + r3 = rays(beam_bwd)[3] + @test r3.n ≈ 1.5 + + # Verify amplitude scaling: transmission from 1.0 to 1.6 (Uncoated), then 1.6 to 1.5 (SimpleARCoating) + expected_amp = (2 * 1.0 / (1.0 + 1.6)) * sqrt(0.99) + pol3 = BMO.polarization(r3) + @test abs(pol3[1]) ≈ expected_amp + end + + @testset "Flat shape coatings checks" begin + # Test degenerate collinear vertex check in is_flat_shape + mesh_3d = BMO.CuboidMesh(1.0, 1.0, 1.0) + # Force the first three vertices to be collinear + mesh_3d.vertices[1, :] = [0.0, 0.0, 0.0] + mesh_3d.vertices[2, :] = [1.0, 0.0, 0.0] + mesh_3d.vertices[3, :] = [2.0, 0.0, 0.0] + @test !BMO.is_flat_shape(mesh_3d) + + # Test ArgumentError on flat shape with both front and back coatings + flat_mesh = BMO.QuadraticFlatMesh(10e-3) + coat1 = SimpleARCoating(0.0) + coat2 = SimpleHRCoating(1.0) + + mirror = Mirror(flat_mesh) + @test_throws ArgumentError with_coatings(mirror, front = coat1, back = coat2) + end + + @testset "Show methods and Display" begin + repr_plain(x) = repr(MIME"text/plain"(), x) + # Test models show + @test repr_plain(Uncoated()) == "Uncoated" + @test repr_plain(SimpleARCoating(0.05)) == "SimpleARCoating(R = 0.05)" + @test repr_plain(SimpleHRCoating(0.98)) == "SimpleHRCoating(R = 0.98)" + @test repr_plain(SimpleBeamsplitterCoating(0.5, 0.5, 0.5, 0.5)) == + "SimpleBeamsplitterCoating(rs = 0.5 + 0.0im, rp = 0.5 + 0.0im, ts = 0.5 + 0.0im, tp = 0.5 + 0.0im)" + @test repr_plain(JonesCoating(BMO.SPBasis(1, 0, 0, 1))) == + "JonesCoating(behavior = Transmissive())" + @test repr_plain(ThinFilmCoating(1.38, 200e-9)) == + "ThinFilmCoating(1 layers, behavior = Transmissive())" + + # Test coated components show + lens = SphericalLens(100e-3, -100e-3, 5e-3, 10e-3, λ -> 1.5) + cl = with_coatings(lens, front = SimpleARCoating(0.02)) + @test cl isa Lens + @test BMO.coatings(cl) != () + + mirror = SquarePlanoMirror2D(10e-3) + cm = with_coatings(mirror, front = SimpleHRCoating(0.99)) + @test cm isa Mirror + @test BMO.coatings(cm) != () + end + + @testset "Absorptive behavior" begin + # Standalone absorptive coating + struct DummyAbsorptiveCoating + behavior::Absorptive + end + BMO.coating_behavior(::DummyAbsorptiveCoating) = Absorptive() + + flat_mesh = BMO.QuadraticFlatMesh(10e-3) + abs_coat = Coating(flat_mesh, DummyAbsorptiveCoating(Absorptive())) + + system = System([abs_coat]) + ray = Ray([0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9) + beam = Beam(ray) + solve_system!(system, beam; retrace = false) + # Ray should be terminated (absorbed) at the interface, so only 1 ray exists in the beam + @test length(rays(beam)) == 1 + + # CoatedRefractive with absorptive coating + cl_abs = SphericalLens(100e-3, -100e-3, 5e-3, 10e-3, λ -> 1.5) |> + with_coatings(front = DummyAbsorptiveCoating(Absorptive())) + system_cl = System([cl_abs]) + beam_cl = Beam(Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9)) + solve_system!(system_cl, beam_cl; retrace = false) + @test length(rays(beam_cl)) == 1 + + # CoatedMirror with absorptive coating + cm_abs = SquarePlanoMirror2D(10e-3) |> + with_coatings(front = DummyAbsorptiveCoating(Absorptive())) + system_cm = System([cm_abs]) + beam_cm = Beam(Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9)) + solve_system!(system_cm, beam_cm; retrace = false) + @test length(rays(beam_cm)) == 1 + end + + @testset "Wavelength-dependent coatings and dynamic behavior" begin + # Dynamic behavior based on ray properties + struct DynamicARCoating end + # behaves as Transmissive for λ < 800nm, Reflective for λ >= 800nm + BMO.coating_behavior(::DynamicARCoating, ray) = BMO.wavelength(ray) < 800e-9 ? + Transmissive() : Reflective() + BMO.get_jones_matrix(::DynamicARCoating, θi, λ, n1, n2, is_reflected; from_front = true, kwargs...) = BMO.SPBasis( + 1.0, 0, 0, 1.0) + + flat_mesh = BMO.QuadraticFlatMesh(10e-3) + dyn_coat = Coating(flat_mesh, DynamicARCoating()) + system = System([dyn_coat]) + + # λ = 600nm -> should transmit + beam_t = Beam(Ray([0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 600e-9)) + solve_system!(system, beam_t; retrace = false) + @test length(rays(beam_t)) == 2 + @test rays(beam_t)[2].dir[2] ≈ 1.0 + + # λ = 900nm -> should reflect + beam_r = Beam(Ray([0.0, -5e-3, 0.0], [0.0, 1.0, 0.0], 900e-9)) + solve_system!(system, beam_r; retrace = false) + @test length(rays(beam_r)) == 2 + @test rays(beam_r)[2].dir[2] ≈ -1.0 + + # ThinFilmCoating with dispersion function n(λ) + n_disp = λ -> λ < 800e-9 ? 1.38 : 1.6 + coat_disp = ThinFilmCoating(n_disp, 200e-9) + rs_short, _, _, _ = fresnel_coefficients(coat_disp, 0.0, 600e-9, 1.0, 1.5) + rs_long, _, _, _ = fresnel_coefficients(coat_disp, 0.0, 900e-9, 1.0, 1.5) + @test rs_short != rs_long + end + + @testset "Coated Doublet Lens" begin + n1 = 1.5 + n2 = 1.6 + ar = SimpleARCoating(0.0) + + doublet = SphericalDoubletLens(50e-3, -50e-3, -100e-3, 5e-3, 3e-3, 25e-3, n1, + n2; front_coating = ar, back_coating = ar) + @test doublet.front isa Lens + @test doublet.back isa Lens + @test BMO.coatings(doublet.front) != () + @test BMO.coatings(doublet.back) != () + + sys = System([doublet]) + beam = Beam(Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], 589e-9)) + solve_system!(sys, beam; retrace = false) + @test length(rays(beam)) == 4 # Initial ray + 3 surface transitions + end + + @testset "CSG UnionSDF Coating Resolution" begin + lens1 = SphericalLens(50e-3, -50e-3, 5e-3, 10e-3, 1.5) + lens2 = SphericalLens(100e-3, -100e-3, 5e-3, 10e-3, 1.5) + translate3d!(lens2, [0.0, 20e-3, 0.0]) + + s1 = BMO.shape(lens1) + s2 = BMO.shape(lens2) + u_shape = s1 + s2 + + p1 = BMO.position(s1) + [0.0, -2.5e-3, 0.0] + p2 = BMO.position(s2) + [0.0, -2.5e-3, 0.0] + + @test BMO.active_constituent_sdf(u_shape, p1) isa BMO.AbstractSphericalSurfaceSDF + @test BMO.active_constituent_sdf(u_shape, p2) isa BMO.AbstractSphericalSurfaceSDF + + n_glass = λ -> 1.5 + struct CompoundLens{T, C <: Tuple} <: + BMO.AbstractRefractiveOptic{T, BMO.RefractiveIndex} + shape::BMO.UnionSDF{T} + n::Function + coatings::C + function CompoundLens(shape::BMO.UnionSDF{T}, n::Function, + coatings::C = ()) where {T, C <: Tuple} + return new{T, C}(shape, n, coatings) + end + end + BMO.shape_trait_of(::CompoundLens) = BMO.SingleShape() + BMO.shape(c::CompoundLens) = c.shape + BMO.refractive_index(c::CompoundLens, λ::Real) = c.n(λ) + BMO._attach_coatings(c::CompoundLens, c_tuple; deepcopy_shape::Bool = false) = CompoundLens( + deepcopy_shape ? deepcopy(c.shape) : c.shape, c.n, c_tuple) + + compound = CompoundLens(u_shape, n_glass) + coated_compound = compound |> with_coatings(front = SimpleARCoating(0.02)) + + sys = System([coated_compound]) + beam = Beam(Ray([0.0, -10e-3, 0.0], [0.0, 1.0, 0.0], 1000e-9)) + solve_system!(sys, beam; retrace = false) + + model1 = BMO.get_coating_model_at_hit(coated_compound, rays(beam)[1]) + @test model1 isa SimpleARCoating + @test model1.R ≈ 0.02 + end + + @testset "Unified Coating Transmittance and Reflectance API" begin + ar = SimpleARCoating(0.01) # R=1% + R = coating_reflectance(ar, 0.0, 1064e-9, 1.0, 1.5) + T = coating_transmittance(ar, 0.0, 1064e-9, 1.0, 1.5) + @test R≈0.01 atol=1e-6 + @test T≈0.99 atol=1e-6 + @test R + T≈1.0 atol=1e-6 + end + + @testset "Analytic Normals and Surface Tags" begin + box = BMO.BoxSDF(10e-3, 20e-3, 30e-3) + p_front = BMO.Point3(0.0, -10e-3, 0.0) + n_analytic_front = BMO.normal3d(box, p_front) + n_fd_front = BMO.normal_fd(box, p_front) + @test n_analytic_front≈n_fd_front atol=1e-4 + @test BMO.surface_tag(box, p_front, n_analytic_front) === :front + + p_back = BMO.Point3(0.0, 10e-3, 0.0) + n_analytic_back = BMO.normal3d(box, p_back) + @test BMO.surface_tag(box, p_back, n_analytic_back) === :back + + cyl = BMO.CylinderSDF(5e-3, 10e-3) + p_top = BMO.Point3(0.0, 5e-3, 0.0) + n_top = BMO.normal3d(cyl, p_top) + @test n_top≈[0.0, 1.0, 0.0] atol=1e-4 + @test BMO.surface_tag(cyl, p_top, n_top) === :top + + p_side = BMO.Point3(5e-3, 0.0, 0.0) + n_side = BMO.normal3d(cyl, p_side) + @test n_side≈[1.0, 0.0, 0.0] atol=1e-4 + @test BMO.surface_tag(cyl, p_side, n_side) === :side + + sph = BMO.SphereSDF(10e-3) + p_sph_front = BMO.Point3(0.0, -10e-3, 0.0) + n_sph_front = BMO.normal3d(sph, p_sph_front) + @test n_sph_front≈[0.0, -1.0, 0.0] atol=1e-4 + @test BMO.surface_tag(sph, p_sph_front, n_sph_front) === :front + + p_sph_back = BMO.Point3(0.0, 10e-3, 0.0) + n_sph_back = BMO.normal3d(sph, p_sph_back) + @test BMO.surface_tag(sph, p_sph_back, n_sph_back) === :back + end + + @testset "AbstractSurfaceModel Hierarchy" begin + @test SimpleARCoating() isa AbstractCoatingModel + @test SimpleARCoating() isa AbstractSurfaceModel + @test Uncoated() isa AbstractSurfaceModel + @test ThinFilmCoating([], []) isa AbstractSurfaceModel + end + + @testset "Multi-Face Selector Syntax" begin + lens = BMO.SphericalLens(25e-3, 50e-3, 50e-3) + coated = BMO.with_coatings(lens, (:front, :back) => BMO.SimpleARCoating(0.01)) + + p_front = BMO.Point3(0.0, -2e-3, 0.0) + p_back = BMO.Point3(0.0, 2e-3, 0.0) + n_front = BMO.Point3(0.0, -1.0, 0.0) + n_back = BMO.Point3(0.0, 1.0, 0.0) + + @test BMO.get_matching_coating( + BMO.coatings(coated), BMO.shape(coated), p_front, n_front) isa + BMO.SimpleARCoating + @test BMO.get_matching_coating( + BMO.coatings(coated), BMO.shape(coated), p_back, n_back) isa BMO.SimpleARCoating + end + + @testset "CompositeSurfaceModel" begin + ar1 = BMO.SimpleARCoating(0.05) # R=0.05, T=0.95 + ar2 = BMO.SimpleARCoating(0.10) # R=0.10, T=0.90 + comp = BMO.CompositeSurfaceModel(ar1, ar2) + @test BMO.coating_behavior(comp) isa BMO.Transmissive + + J = BMO.get_jones_matrix(comp, 0.0, 632.8e-9, 1.0, 1.5, false) + T_val = BMO.unpolarized_transmittance(J) + @test T_val≈(0.95 * 0.90) atol=1e-4 + end + + @testset "deepcopy_shape option in with_coatings" begin + lens = BMO.SphericalLens(25e-3, 50e-3, 50e-3) + c1 = BMO.with_coatings( + lens, :front => BMO.SimpleARCoating(0.01); deepcopy_shape = false) + c2 = BMO.with_coatings( + lens, :front => BMO.SimpleARCoating(0.01); deepcopy_shape = true) + + @test c1.shape === lens.shape + @test c2.shape !== lens.shape + end + + @testset "GradedThinFilmCoating" begin + tf = BMO.ThinFilmCoating([1.38], [150e-9]) + graded = BMO.GradedThinFilmCoating(p -> 1.0 + 0.1 * p[1], tf) + @test BMO.coating_behavior(graded) isa BMO.Transmissive + + p1 = BMO.Point3(0.0, 0.0, 0.0) + p2 = BMO.Point3(1.0, 0.0, 0.0) + + J1 = BMO.get_jones_matrix(graded, 0.0, 632.8e-9, 1.0, 1.5, false; local_p = p1) + J2 = BMO.get_jones_matrix(graded, 0.0, 632.8e-9, 1.0, 1.5, false; local_p = p2) + + @test BMO.unpolarized_transmittance(J1) != BMO.unpolarized_transmittance(J2) + end + + @testset "Coating Engine Bug Prevention & Surface Tag Contracts" begin + # Test surface_tag 1-arg vs 3-arg contract on translated/rotated Lens SDFs + lens = SphericalLens(25.0e-3, 50.0e-3, 5.0e-3, 10.0e-3) # thickness = 5mm, y ranges from 0 to 5mm + translate3d!(lens, [1.0e-3, 2.0e-3, 3.0e-3]) + zrotate3d!(lens, π / 4) + + shape_lens = BMO.shape(lens) + world_front_pt = position(lens) + orientation(lens) * BMO.Point3(0.0, -1.0e-3, 0.0) # y < 0 + world_back_pt = position(lens) + orientation(lens) * BMO.Point3(0.0, 6.0e-3, 0.0) # y > 5mm + + # 1-arg surface_tag takes world coordinates and returns correct tag + @test BMO.surface_tag(shape_lens, world_front_pt) === :front + @test BMO.surface_tag(shape_lens, world_back_pt) === :back + + # 3-arg surface_tag takes local coordinates and returns identical tag + local_front_pt = BMO._world_to_sdf(shape_lens, world_front_pt) + local_back_pt = BMO._world_to_sdf(shape_lens, world_back_pt) + @test BMO.surface_tag(shape_lens, local_front_pt, BMO.Point3(0.0, -1.0, 0.0)) === + :front + @test BMO.surface_tag(shape_lens, local_back_pt, BMO.Point3(0.0, 1.0, 0.0)) === + :back + + # Test spatial hit position resolution in resolve_coated_boundary + # Front face has AR coating (R=0), back face has Beamsplitter coating (R=0.8) + ar_coat = SimpleARCoating(0.0) + bs_coat = SimpleBeamsplitterCoating(0.8, 0.8, 0.2, 0.2) + coated_lens = lens |> with_coatings(front = ar_coat, back = bs_coat) + + sys = System([coated_lens]) + + # Ray starting outside front face targeting lens (s-polarized along z-axis) + ray_dir = orientation(lens) * BMO.Point3(0.0, 1.0, 0.0) + ray_in = PolarizedRay( + world_front_pt - 10.0e-3 * ray_dir, ray_dir, 632.8e-9, [0.0, 0.0, 1.0]) + beam_in = Beam(ray_in) + solve_system!(sys, beam_in; retrace = false) + ray_hit = BMO.rays(beam_in)[1] + + # Test boundary resolution at hit point (front face) + _, coating_front = BMO.resolve_coated_boundary(sys, coated_lens, ray_hit) + @test coating_front === ar_coat + + # Substrate object identity matching in interface context + # Check that shape matching detects substrate correctly (6th return element is is_substrate) + ctx = BMO._resolve_interface_context(sys, coated_lens, ray_hit) + @test ctx[6] === true # is_substrate is true for coated_lens + + # Fabry-Pérot cavity tracing onto detector test + m1 = SphericalLens(Inf, Inf, 0.5e-3, 5.0e-3) |> + with_coatings(front = SimpleBeamsplitterCoating(0.8, 0.8, 0.2, 0.2), + back = SimpleARCoating(0.0)) + m2 = SphericalLens(Inf, Inf, 0.5e-3, 5.0e-3) |> + with_coatings(front = SimpleBeamsplitterCoating(0.8, 0.8, 0.2, 0.2), + back = SimpleARCoating(0.0)) + translate3d!(m2, [0.0, 1.0e-3, 0.0]) + + det = Detector(10.0e-3) + translate3d!(det, [0.0, 5.0e-3, 0.0]) + + fp_sys = System([m1, m2, det]) + fp_beam = Beam(PolarizedRay( + [0.0, -1.0e-3, 0.0], [0.0, 1.0, 0.0], 632.8e-9, [0.0, 0.0, 1.0])) + solve_system!(fp_sys, fp_beam; r_max = 50, depth_max = 12, retrace = false) + + @test !isnothing(BMO.hits(det)) && length(BMO.hits(det)) > 0 + end + + @testset "Audit Improvements: Layer TIR Robustness & AD Compatibility" begin + # Real-index layer TIR in TMM without DomainError + # Layer index nl = 1.2, incident n1 = 1.5, substrate n2 = 1.5. + # At θi = 60° (sin 60° ≈ 0.866), n1 * sinθi = 1.299 > 1.2 -> TIR occurs inside layer! + θ_tir = π / 3 + coat_low_index = ThinFilmCoating(1.2, 500e-9) + rs, rp, ts, tp = BMO.fresnel_coefficients(coat_low_index, θ_tir, 1000e-9, 1.5, 1.5) + @test rs isa Complex + @test rp isa Complex + @test ts isa Complex + @test tp isa Complex + # Energy conservation check + R_val = coating_reflectance(coat_low_index, θ_tir, 1000e-9, 1.5, 1.5) + T_val = coating_transmittance(coat_low_index, θ_tir, 1000e-9, 1.5, 1.5) + @test R_val + T_val≈1.0 atol=1e-5 + + # Parametric Coatings + ar_f32 = SimpleARCoating(Float32(0.01)) + @test ar_f32.R isa Float32 + hr_f32 = SimpleHRCoating(Float32(0.99)) + @test hr_f32.R isa Float32 + bs_gen = SimpleBeamsplitterCoating(0.5, 0.5, 0.5, 0.5) + @test bs_gen.rs isa ComplexF64 + + # ForwardDiff / Automatic Differentiation through ThinFilmCoating + using ForwardDiff + # Compute gradient of transmittance with respect to layer thickness d + λ_test = 632.8e-9 + calc_trans = d -> begin + c = ThinFilmCoating(1.38, d) + coating_transmittance(c, 0.0, λ_test, 1.0, 1.5) + end + # Quarter wave thickness: d0 = λ / (4 * 1.38) + d0 = λ_test / (4 * 1.38) + grad_d = ForwardDiff.derivative(calc_trans, d0) + # At optimal AR thickness, transmittance is at a local extremum -> derivative is ~0 + @test abs(grad_d) < 1e-4 + end + + @testset "WOLIT Trap and Coated Mirrors" begin + # Custom coating for WOLIT filter + struct WolitTestCoating + lambda_0::Float64 + n_eff::Float64 + laser_lambda::Float64 + transmissive_model::SimpleARCoating{Float64} + reflective_model::SimpleHRCoating{Float64} + end + WolitTestCoating(l0, ne, ll) = WolitTestCoating(l0, ne, ll, SimpleARCoating(0.02), SimpleHRCoating(0.999)) + + function BMO.coating_behavior(coating::WolitTestCoating, ray) + int = BMO.intersection(ray) + normal = BMO.normal3d(int) + n_incident = BMO.refractive_index(ray) + cos_θ = abs(dot(BMO.direction(ray), normal)) + sin_θ = sqrt(max(0.0, 1.0 - cos_θ^2)) + sin_θ_air = n_incident * sin_θ + sin_θ_air = clamp(sin_θ_air, 0.0, 1.0) + λ_edge = coating.lambda_0 * sqrt(1.0 - sin_θ_air^2 / coating.n_eff^2) + return coating.laser_lambda > λ_edge ? Transmissive() : Reflective() + end + + function BMO.get_jones_matrix(coating::WolitTestCoating, θi, λ, n1, n2, is_reflected; from_front = true) + sin_θ_air = clamp(n1 * sin(θi), 0.0, 1.0) + λ_edge = coating.lambda_0 * sqrt(1.0 - sin_θ_air^2 / coating.n_eff^2) + if coating.laser_lambda > λ_edge + return BMO.get_jones_matrix(coating.transmissive_model, θi, λ, n1, n2, is_reflected; from_front = from_front) + else + return BMO.get_jones_matrix(coating.reflective_model, θi, λ, n1, n2, is_reflected; from_front = from_front) + end + end + + λ_w = 632.8e-9 + wolit_c = WolitTestCoating(650e-9, 1.85, λ_w) + α_w = deg2rad(1.2) + + m1_b = RectangularPlanoMirror(15e-3, 2e-3, 0.25e-3) + mir1 = with_coatings(m1_b; front = SimpleHRCoating(0.999)) + translate3d!(mir1, [0.0, 1.0e-3, 0.0]) + zrotate3d!(mir1, -α_w / 2) + + m2_b = RectangularPlanoMirror(15e-3, 2e-3, 0.25e-3) + mir2 = with_coatings(m2_b; front = SimpleARCoating(0.0), back = wolit_c) + translate3d!(mir2, [0.0, -0.25e-3, 0.0]) + zrotate3d!(mir2, α_w / 2) + + wolit_sys = System([mir1, mir2]) + ray_in = PolarizedRay([-5.5e-3, -2.5e-3, 0.0], [sin(deg2rad(26.5)), cos(deg2rad(26.5)), 0.0], λ_w, [0.0, 0.0, 1.0]) + wolit_beam = Beam(ray_in) + solve_system!(wolit_sys, wolit_beam; r_max = 200, retrace = false) + + @test length(rays(wolit_beam)) == 48 + end +end + diff --git a/test/Components/TestPolarizers.jl b/test/Components/TestPolarizers.jl index fbde78fa2..2fadeffeb 100644 --- a/test/Components/TestPolarizers.jl +++ b/test/Components/TestPolarizers.jl @@ -15,7 +15,7 @@ const mm = 1e-3 malus_law(θ) = cosd(θ)^2 function generate_linpol_angles(thetas) angles = zeros(length(thetas)) - # consider flip in angle quadrant above 90° + # consider flip in angle quadrant above 90° for i in eachindex(thetas) theta = thetas[i] - 1 if theta > 90 && theta <= 270 @@ -33,7 +33,7 @@ const mm = 1e-3 J = BMO.XYBasis(1, 2, 3, 4) R = [1 2 0; 3 4 0; 0 0 1] @test J == R - @test J*2 == R*2 + @test J * 2 == R * 2 @test transpose(J) == transpose(R) @test inv(J) ≈ inv(R) end @@ -48,22 +48,22 @@ const mm = 1e-3 angles_n = similar(i_n) angles_a = generate_linpol_angles(thetas) - @testset "Pol. filter normal incidence - rotation around y-axis" begin + @testset "Pol. filter normal incidence - rotation around y-axis" begin Rfil = orientation(filter) - ray_dir = Rfil[:,2] + ray_dir = Rfil[:, 2] ray_pos = position(filter) - 10mm * ray_dir - local_x = Rfil[:,1] - local_z = Rfil[:,3] + local_x = Rfil[:, 1] + local_z = Rfil[:, 3] pol_vec = local_x lambda = 1e-6 - beam = Beam(ray_pos, ray_dir, lambda, pol_vec) - # step ref. vector by angle increment + beam = Beam(ray_pos, ray_dir, lambda, pol_vec) + # step ref. vector by angle increment RotMat = BMO.rotate3d(ray_dir, deg2rad(step(thetas))) for i in eachindex(thetas) solve_system!(system, beam) E1 = BMO.polarization(BMO.rays(beam)[2]) i_n[i] = pseudo_I(E1) - i_a[i] = malus_law(thetas[i]-1) + i_a[i] = malus_law(thetas[i] - 1) rotate3d!(filter, ray_dir, deg2rad(step(thetas))) # test polarization state @test all(BMO.islinear.(beam.rays)) @@ -72,21 +72,21 @@ const mm = 1e-3 angles_n[i] = rad2deg(BMO.angle3d(v1, pol_vec)) # update ref vector pol_vec = RotMat * pol_vec - end + end @test angles_n ≈ angles_a end # Move and rotate filter - translate3d!(filter, [0,10mm,0]) + translate3d!(filter, [0, 10mm, 0]) xrotate3d!(filter, deg2rad(45)) zrotate3d!(filter, deg2rad(30)) @testset "Pol. filter tilted incidence - rotation around ray optical axis" begin Rfil = orientation(filter) - ray_dir = Rfil[:,2] + ray_dir = Rfil[:, 2] ray_pos = position(filter) - 10mm * ray_dir - local_x = Rfil[:,1] - local_z = Rfil[:,3] + local_x = Rfil[:, 1] + local_z = Rfil[:, 3] pol_vec = local_x lambda = 1e-6 beam = Beam(ray_pos, ray_dir, lambda, pol_vec) @@ -105,6 +105,362 @@ const mm = 1e-3 @test i_n_tilt ≈ i_a_tilt end end + + @testset "Polarizing Cube Beamsplitter" begin + # PBS cube of leg length 25mm, index n = 1.5 + pbs = PolarizingCubeBeamsplitter(25e-3, n -> 1.5) + translate3d!(pbs, [0, 50mm, 0]) + system = System([pbs]) + + @testset "s-polarization (reflected)" begin + # s-polarization is along z-axis, perpendicular to the plane of incidence (x-y) + beam = Beam([0, 0, 0], [0, 1, 0], 1e-6, [0, 0, 1]) + solve_system!(system, beam) + + # Transmitted beam (children[1]) should have 0 amplitude for s + # Reflected beam (children[2]) should have full amplitude for s + @test length(beam.children) == 2 + t_rays = BMO.rays(beam.children[1]) + r_rays = BMO.rays(beam.children[2]) + @test norm(BMO.polarization(last(t_rays)))≈0.0 atol=1e-12 + @test norm(BMO.polarization(last(r_rays)))≈0.96 atol=1e-12 + @test BMO.direction(last(r_rays)) ≈ [-1, 0, 0] + end + + @testset "p-polarization (transmitted)" begin + # p-polarization is in the x-y plane, along x-axis + beam = Beam([0, 0, 0], [0, 1, 0], 1e-6, [1, 0, 0]) + solve_system!(system, beam) + + # Transmitted beam (children[1]) should have full amplitude for p (with interface loss) + # Reflected beam (children[2]) should have 0 amplitude for p + @test length(beam.children) == 2 + t_rays = BMO.rays(beam.children[1]) + r_rays = BMO.rays(beam.children[2]) + @test norm(BMO.polarization(last(t_rays)))≈0.96 atol=1e-12 + @test norm(BMO.polarization(last(r_rays)))≈0.0 atol=1e-12 + @test BMO.direction(last(t_rays)) ≈ [0, 1, 0] + end + end + + @testset "Waveplates" begin + @testset "Flat Half-Wave Plate (round)" begin + # Fast axis oriented at 22.5 degrees around y-axis. + hwp = HalfWavePlate(5mm; fast_axis_angle = deg2rad(22.5)) + system = System([hwp]) + # Incident polarization along x-axis + beam = Beam([0, -10mm, 0], [0, 1, 0], 1e-6, [1, 0, 0]) + solve_system!(system, beam) + + # Rotation by 2*theta = 45 degrees, so polarization should be along [1, 0, 1]/sqrt(2) + E = BMO.polarization(last(beam.rays)) + @test abs(dot(E, [1.0, 0.0, 1.0] / sqrt(2)))≈1.0 atol=1e-6 + end + + @testset "Flat Half-Wave Plate (rectangular)" begin + # Fast axis oriented at 45 degrees around y-axis. + hwp = HalfWavePlate(5mm, 5mm; fast_axis_angle = deg2rad(45.0)) + system = System([hwp]) + # Incident polarization along x-axis + beam = Beam([0, -10mm, 0], [0, 1, 0], 1e-6, [1, 0, 0]) + solve_system!(system, beam) + + # Rotation by 2*theta = 90 degrees, so polarization should be along z-axis [0, 0, 1] + E = BMO.polarization(last(beam.rays)) + @test abs(dot(E, [0.0, 0.0, 1.0]))≈1.0 atol=1e-6 + end + + @testset "Flat Quarter-Wave Plate" begin + # Fast axis along x-axis (0 degrees) + qwp = QuarterWavePlate(5mm; fast_axis_angle = 0.0) + system = System([qwp]) + # Incident polarization at 45 degrees in x-z plane + beam = Beam([0, -10mm, 0], [0, 1, 0], 1e-6, [1, 0, 1] / sqrt(2)) + solve_system!(system, beam) + + # Output should be circularly polarized + E = BMO.polarization(last(beam.rays)) + @test abs(E[1])≈1 / sqrt(2) atol=1e-6 + @test abs(E[3])≈1 / sqrt(2) atol=1e-6 + @test abs(dot(E, [1, 0, im] / sqrt(2)))≈1.0 atol=1e-6 + end + + @testset "Thick/Plate Half-Wave Plate" begin + # 1mm thick substrate of index n = 1.5, fast axis at 22.5 degrees + hwp_plate = HalfWavePlate(5mm, 1mm, n -> 1.5; fast_axis_angle = deg2rad(22.5)) + system = System([hwp_plate]) + + # Incident polarization along x-axis at normal incidence + beam = Beam([0, -10mm, 0], [0, 1, 0], 1e-6, [1, 0, 0]) + solve_system!(system, beam) + + # Output polarization should still be rotated by 45 degrees + E = BMO.polarization(last(beam.rays)) + @test abs(dot(normalize(E), [1.0, 0.0, 1.0] / sqrt(2)))≈1.0 atol=1e-6 + # Substrate thickness is 1mm, so total propagation distance from -10mm should exit at y = 1mm (i.e. total delta 11mm) + # Since substrate front face is at y = 0, back face is at y = 1mm. + @test BMO.position(last(beam.rays))[2]≈1mm atol=1e-6 + end + + @testset "Round waveplate uses circular mesh" begin + hwp = BMO.HalfWaveplate(0.01) + @test size(BMO.faces(BMO.shape(hwp)), 1) == 30 + qwp = BMO.QuarterWaveplate(0.01) + @test size(BMO.faces(BMO.shape(qwp)), 1) == 30 + end + + @testset "Half-waveplate rotates linear polarization" begin + hwp = BMO.HalfWaveplate(0.01, 0.01) + BMO.yrotate3d!(hwp, deg2rad(30)) + system = StaticSystem([hwp]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + E = BMO.polarization(last(BMO.rays(beam))) + @test abs2(E[1]) / abs2(E0)≈cosd(60)^2 atol=1e-6 + @test abs2(E[3]) / abs2(E0)≈sind(60)^2 atol=1e-6 + end + + @testset "Wavelength dependent retardance" begin + λ0 = 1000e-9 + retardance(λ) = π * (λ / λ0) + hwp = BMO.Waveplate(0.01, 0.01, retardance) + BMO.yrotate3d!(hwp, deg2rad(30)) + system = StaticSystem([hwp]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], λ0, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + E = BMO.polarization(last(BMO.rays(beam))) + @test abs2(E[1]) / abs2(E0)≈cosd(60)^2 atol=1e-6 + @test abs2(E[3]) / abs2(E0)≈sind(60)^2 atol=1e-6 + end + + @testset "Arbitrary Jones matrix" begin + J = BMO.XZBasis(0, 1, 1, 0) + wp = BMO.Waveplate(0.01, 0.01, J) + system = StaticSystem([wp]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + E = BMO.polarization(last(BMO.rays(beam))) + @test abs2(E[3]) / abs2(E0)≈1 atol=1e-6 + end + + @testset "Plate Waveplate Constructor Type Promotion" begin + n = λ -> 1.5 + rpwp = BMO.RectangularPlateWaveplate(10, 10, 1, n, π/2) + @test rpwp isa BMO.RectangularPlateWaveplate{Float64} + + round_pwp = BMO.RoundPlateWaveplate(10, 1, n, π/2) + @test round_pwp isa BMO.RoundPlateWaveplate{Float64} + + hwp_rect = BMO.HalfWavePlate(10, 10, 1, n) + @test hwp_rect isa BMO.RectangularPlateWaveplate{Float64} + + qwp_round = BMO.QuarterWavePlate(10, 1, n) + @test qwp_round isa BMO.RoundPlateWaveplate{Float64} + end + + @testset "Quarter-waveplate creates circular polarization" begin + qwp = BMO.QuarterWaveplate(0.01, 0.01) + BMO.yrotate3d!(qwp, deg2rad(45)) + system = StaticSystem([qwp]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + E = BMO.polarization(last(BMO.rays(beam))) + @test abs(E[1])≈abs(E[3]) atol=1e-6 + @test angle(E[3]) - angle(E[1])≈π / 2 atol=1e-6 + end + + @testset "Polarizing beam splitter separates linear polarizations" begin + pbs = BMO.PolarizingBeamSplitter(0.01, 0.01) + BMO.translate3d!(pbs, [0, 0.01, 0]) + system = StaticSystem([pbs]) + E0 = BMO.electric_field(1) + + rayx = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beamx = Beam(rayx) + solve_system!(system, beamx) + tx = BMO.polarization(first(BMO.rays(beamx.children[1]))) + rx = BMO.polarization(first(BMO.rays(beamx.children[2]))) + @test abs2(tx[1]) / abs2(E0)≈1 atol=1e-6 + @test abs2(rx[3]) / abs2(E0)≈0 atol=1e-6 + + rayz = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [0, 0, E0]) + beamz = Beam(rayz) + solve_system!(system, beamz) + tz = BMO.polarization(first(BMO.rays(beamz.children[1]))) + rz = BMO.polarization(first(BMO.rays(beamz.children[2]))) + @test abs2(tz[1]) / abs2(E0)≈0 atol=1e-6 + @test abs2(rz[3]) / abs2(E0)≈1 atol=1e-6 + end + + @testset "HWP before polarizing beamsplitter" begin + hwp = BMO.HalfWaveplate(0.01, 0.01) + BMO.yrotate3d!(hwp, deg2rad(22.5)) + pbs = BMO.PolarizingBeamSplitter(0.01, 0.01) + BMO.translate3d!(pbs, [0, 0.01, 0]) + system = StaticSystem([hwp, pbs]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + tE = BMO.polarization(first(BMO.rays(beam.children[1]))) + rE = BMO.polarization(first(BMO.rays(beam.children[2]))) + It = abs2(tE[1]) / abs2(E0) + Ir = abs2(rE[3]) / abs2(E0) + @test It + Ir≈1 atol=1e-6 + @test It > 0 && Ir > 0 + end + + @testset "HWP before polarizing cube beamsplitter" begin + hwp = BMO.HalfWaveplate(0.01, 0.01) + BMO.yrotate3d!(hwp, deg2rad(22.5)) + pcbs = BMO.PolarizingCubeBeamsplitter(0.01, n -> 1.0) + BMO.translate3d!(pcbs, [0, 0.015, 0]) + system = StaticSystem([hwp, pcbs]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + @test !isempty(BMO.rays(beam.children[1])) + @test !isempty(BMO.rays(beam.children[2])) + end + + @testset "HWP before tilted polarizing cube beamsplitter" begin + hwp = BMO.HalfWaveplate(0.01, 0.01) + BMO.yrotate3d!(hwp, deg2rad(22.5)) + pcbs = BMO.PolarizingCubeBeamsplitter(0.01, n -> 1.0) + BMO.translate3d!(pcbs, [0, 0.015, 0]) + BMO.xrotate3d!(pcbs, deg2rad(10)) + system = StaticSystem([hwp, pcbs]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + @test !isempty(BMO.rays(beam.children[1])) + @test !isempty(BMO.rays(beam.children[2])) + end + + @testset "Polarizing plate beamsplitter splits 45° polarization" begin + ppbs = BMO.RectangularPolarizingPlateBeamsplitter(0.01, 0.01, 0.005, n -> 1.0) + BMO.translate3d!(ppbs, [0, 0.01, 0]) + system = StaticSystem([ppbs]) + E0 = BMO.electric_field(1) + E = E0 / sqrt(2) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E, 0, E]) + beam = Beam(ray) + solve_system!(system, beam) + tE = BMO.polarization(last(BMO.rays(beam.children[1]))) + rE = BMO.polarization(last(BMO.rays(beam.children[2]))) + It = abs2(tE[1]) / abs2(E0) + Ir = abs2(rE[3]) / abs2(E0) + @test It≈0.5 atol=1e-6 + @test Ir≈0.5 atol=1e-6 + end + + @testset "QWP mirror roundtrip" begin + qwp = BMO.QuarterWaveplate(0.01, 0.01) + BMO.yrotate3d!(qwp, deg2rad(45)) + mir = BMO.Mirror(BMO.RectangularFlatMesh(0.02, 0.02)) + BMO.translate3d!(mir, [0, 0.02, 0]) + system = StaticSystem([qwp, mir]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [E0, 0, 0]) + beam = Beam(ray) + solve_system!(system, beam) + finalE = BMO.polarization(last(BMO.rays(beam))) + Ix = abs2(finalE[1]) / abs2(E0) + Iz = abs2(finalE[3]) / abs2(E0) + @test Ix≈0 atol=1e-6 + @test Iz≈1 atol=1e-6 + end + + @testset "Roundtrip with HWP, PBSC, QWP, mirror" begin + hwp = BMO.HalfWaveplate(0.01, 0.01) + BMO.yrotate3d!(hwp, deg2rad(45)) + pcbs = BMO.PolarizingCubeBeamsplitter(0.01, n -> 1.0) + BMO.translate3d!(pcbs, [0, 0.015, 0]) + qwp = BMO.QuarterWaveplate(0.01, 0.01) + BMO.yrotate3d!(qwp, deg2rad(45)) + BMO.translate3d!(qwp, [0, 0.03, 0]) + mir = BMO.Mirror(BMO.RectangularFlatMesh(0.02, 0.02)) + BMO.translate3d!(mir, [0, 0.05, 0]) + system = StaticSystem([hwp, pcbs, qwp, mir]) + E0 = BMO.electric_field(1) + ray = PolarizedRay([0, -0.05, 0], [0, 1.0, 0], 1000e-9, [0, 0, E0]) + beam = Beam(ray) + solve_system!(system, beam) + rE0 = BMO.polarization(first(BMO.rays(beam.children[2]))) + @test abs2(rE0[3]) / abs2(E0)≈0 atol=1e-6 + rE = BMO.polarization(first(BMO.rays(beam.children[1].children[2]))) + Ir = abs2(rE[3]) / abs2(E0) + @test Ir≈1 atol=1e-6 + end + + @testset "AstigmaticGaussianBeamlet with Polarizers" begin + # PolarizationFilter + filter = PolarizationFilter(20mm) + system1 = System([filter]) + agb1 = AstigmaticGaussianBeamlet( + [0.0, -50mm, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1mm; + E0 = [1.0, 0.0, 0.0], support = [0.0, 0.0, 1.0]) + solve_system!(system1, agb1) + # Should pass through with polarization preserved + @test BMO.polarization(last(BMO.rays(agb1.c))) ≈ [1.0, 0.0, 0.0] + + # Waveplate + hwp = HalfWaveplate(20mm, 20mm) + BMO.yrotate3d!(hwp, deg2rad(30)) + system2 = System([hwp]) + agb2 = AstigmaticGaussianBeamlet( + [0.0, -50mm, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1mm; + E0 = [1.0, 0.0, 0.0], support = [0.0, 0.0, 1.0]) + solve_system!(system2, agb2) + # Final polarization vector rotated to [cos(60°), 0, -sin(60°)] (with -im global phase) + final_pol = BMO.polarization(last(BMO.rays(agb2.c))) + expected = [cosd(60), 0.0, -sind(60)] + @test final_pol ≈ -im * expected atol=1e-6 + end + end + + @testset "Power Cutoff in solve_system!" begin + bs = ThinBeamsplitter(5mm, 5mm; reflectance = 0.5) + m = SquarePlanoMirror2D(5mm) + translate3d!(m, [0.0, 20mm, 0.0]) + zrotate3d!(m, deg2rad(10.0)) + system = System([bs, m]) + + # Test 1: No power cutoff (default 0.0) -> traces all children + beam_no_cut = Beam([0.0, -10mm, 0.0], [0.0, 1.0, 0.0], 1e-6, [1.0, 0.0, 0.0]) + solve_system!(system, beam_no_cut) + @test length(beam_no_cut.children) == 2 + # Transmitted child propagates to mirror, so it has 2 rays + @test length(BMO.rays(beam_no_cut.children[1])) == 2 + # Reflected child has no obstacles, so it has 1 ray + @test length(BMO.rays(beam_no_cut.children[2])) == 1 + + # Test 2: power_cutoff = 0.6 -> cuts off children since child power (0.5) < 0.6 + beam_cut = Beam([0.0, -10mm, 0.0], [0.0, 1.0, 0.0], 1e-6, [1.0, 0.0, 0.0]) + solve_system!(system, beam_cut; power_cutoff = 0.6) + @test length(beam_cut.children) == 2 + # Child beams were cut off, so they have only 1 ray (the start/interaction ray) + @test length(BMO.rays(beam_cut.children[1])) == 1 + @test length(BMO.rays(beam_cut.children[2])) == 1 + + # Test 3: Standard unpolarized Ray power cutoff + beam_unpol = Beam([0.0, -10mm, 0.0], [0.0, 1.0, 0.0], 1e-6) + solve_system!(system, beam_unpol; power_cutoff = 0.6) + @test length(beam_unpol.children) == 2 + # Cutoff should also happen here because reflectance=0.5 < 0.6 + @test length(BMO.rays(beam_unpol.children[1])) == 1 + @test length(BMO.rays(beam_unpol.children[2])) == 1 + end end -end # MODULE \ No newline at end of file +end # MODULE diff --git a/test/Components/TestPolarizingBeamsplitters.jl b/test/Components/TestPolarizingBeamsplitters.jl new file mode 100644 index 000000000..744c297ac --- /dev/null +++ b/test/Components/TestPolarizingBeamsplitters.jl @@ -0,0 +1,151 @@ +module TestPolarizingBeamsplitters + +using BeamletOptics +using Test +using LinearAlgebra +using AbstractTrees + +const BMO = BeamletOptics +const mm = 1e-3 + +@testset "Polarizing Beamsplitters" begin + @testset "Polarizing PlateBeamsplitter Constructor Type Promotion" begin + n(λ) = 1.5 + # Passing integer dimensions to RectangularPolarizingPlateBeamsplitter + rppbs = RectangularPolarizingPlateBeamsplitter(10, 10, 2, n) + @test rppbs isa RectangularPolarizingPlateBeamsplitter{Float64} + @test BMO.shape(rppbs) isa BMO.BoxSDF{Float64} + @test BMO.coatings(rppbs)[1].second isa BMO.JonesCoating + + # Passing integer dimensions to RoundPolarizingPlateBeamsplitter + round_ppbs = RoundPolarizingPlateBeamsplitter(20, 2, n) + @test round_ppbs isa RoundPolarizingPlateBeamsplitter{Float64} + @test BMO.shape(round_ppbs) isa BMO.PlanoSurfaceSDF{Float64} + @test BMO.coatings(round_ppbs)[1].second isa BMO.JonesCoating + end + + @testset "RectangularPolarizingPlateBeamsplitter (n > 1)" begin + # Substrate n=1.5 + n_val = 1.5 + n(λ) = n_val + width = 10mm + height = 10mm + thickness = 2mm + + # Create PPBS + ppbs = RectangularPolarizingPlateBeamsplitter(width, height, thickness, n) + + system = StaticSystem([ppbs]) + + angle_deg = 15 + # Coming from -y, moving +y. Tilted in +x. + ki = normalize([sind(angle_deg), cosd(angle_deg), 0]) + + # P-pol (in plane of incidence, xy-plane) -> should be transmitted + E0_p = normalize([cosd(angle_deg), -sind(angle_deg), 0]) + + # Start at y = -10mm + ray_p = PolarizedRay([0, -10mm, 0], ki, 1000e-9, E0_p) + beam_p = Beam(ray_p) + solve_system!(system, beam_p) + + trans_ray_p = first(BMO.rays(beam_p.children[1])) + refl_ray_p = first(BMO.rays(beam_p.children[2])) + + th2 = asin(sind(angle_deg) / 1.5) + expected_dir = [sin(th2), cos(th2), 0] + @test BMO.direction(trans_ray_p)≈expected_dir atol=1e-6 + + # Check orthogonality + @test abs(dot(BMO.direction(trans_ray_p), BMO.polarization(trans_ray_p))) < 1e-9 + + # Power Conservation Test + leaves = collect(AbstractTrees.Leaves(beam_p)) + total_power_out = sum(BMO.refractive_index(last(BMO.rays(leaf))) * + norm(BMO.polarization(last(BMO.rays(leaf))))^2 + for leaf in leaves) + power_in = BMO.refractive_index(ray_p) * norm(E0_p)^2 + + @test total_power_out < power_in + @test total_power_out > 0.9 * power_in + end + + @testset "PolarizingCubeBeamsplitter (n > 1)" begin + n_val = 1.5 + n(λ) = n_val + L = 20mm + + pcbs = PolarizingCubeBeamsplitter(L, n) + + system = StaticSystem([pcbs]) + + angle_deg = 10 + ki = normalize([sind(angle_deg), -cosd(angle_deg), 0]) + + # P-pol (in plane) + E0_p = normalize([-ki[2], ki[1], 0]) + + ray = PolarizedRay([0, 2 * L, 0], ki, 1000e-9, E0_p) + beam = Beam(ray) + solve_system!(system, beam) + + # Check children (Transmission) + leaves = collect(AbstractTrees.Leaves(beam)) + total_power_out = sum(BMO.refractive_index(last(BMO.rays(leaf))) * + norm(BMO.polarization(last(BMO.rays(leaf))))^2 + for leaf in leaves) + power_in = BMO.refractive_index(ray) * norm(E0_p)^2 + @test total_power_out < power_in + @test total_power_out > 0.9 * power_in + end + + @testset "Pi phase jump for PCBS reflection" begin + pcbs = PolarizingCubeBeamsplitter(20mm, n -> 1.5) + system = StaticSystem([pcbs]) + + # Ray along y, z-polarized + ki = [0.0, 1.0, 0.0] + E0_z = [0.0, 0.0, 1.0] + ray = PolarizedRay([0, -20mm, 0], ki, 1000e-9, E0_z) + beam = Beam(ray) + solve_system!(system, beam) + + leaves = collect(AbstractTrees.Leaves(beam)) + + refl_rays = filter(l -> abs(BMO.direction(last(BMO.rays(l)))[1]) > 0.9, leaves) + @test !isempty(refl_rays) + refl_ray = last(BMO.rays(first(refl_rays))) + + # Check that Ez is flipped + @test real(BMO.polarization(refl_ray)[3])≈0.96 atol=1e-6 + end + + @testset "AstigmaticGaussianBeamlet with Polarizing Beamsplitters" begin + # Thin PolarizingBeamSplitter + pbs = PolarizingBeamSplitter(20mm, 20mm) + system1 = System([pbs]) + agb1 = AstigmaticGaussianBeamlet([0.0, -50mm, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1mm; + E0 = [1.0, 0.0, 1.0] / sqrt(2), support = [1.0, 0.0, 0.0]) + solve_system!(system1, agb1) + @test length(children(agb1)) == 2 + @test isa(children(agb1)[1], AstigmaticGaussianBeamlet) + @test isa(children(agb1)[2], AstigmaticGaussianBeamlet) + + # PolarizingCubeBeamsplitter + pcbs = PolarizingCubeBeamsplitter(20mm, n -> 1.0) + system2 = System([pcbs]) + agb2 = AstigmaticGaussianBeamlet([0.0, -50mm, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1mm; + E0 = [1.0, 0.0, 1.0] / sqrt(2), support = [1.0, 0.0, 0.0]) + solve_system!(system2, agb2) + @test length(children(agb2)) == 2 + + # RectangularPolarizingPlateBeamsplitter + ppbs = RectangularPolarizingPlateBeamsplitter(20mm, 20mm, 5mm, n -> 1.0) + system3 = System([ppbs]) + agb3 = AstigmaticGaussianBeamlet([0.0, -50mm, 0.0], [0.0, 1.0, 0.0], 1000e-9, 1mm; + E0 = [1.0, 0.0, 1.0] / sqrt(2), support = [1.0, 0.0, 0.0]) + solve_system!(system3, agb3) + @test length(children(agb3)) == 2 + end +end +end diff --git a/test/E2E/TestMachZehnder.jl b/test/E2E/TestMachZehnder.jl index 720a3c478..5c1b7e160 100644 --- a/test/E2E/TestMachZehnder.jl +++ b/test/E2E/TestMachZehnder.jl @@ -50,7 +50,7 @@ const BMO = BeamletOptics @test r[3] ≈ -sqrt(2) / 2 @test tr[3] ≈ -sqrt(2) / 2 @test rr[3] ≈ sqrt(2) / 2 - @test trt ≈ rrr + @test trt ≈ -rrr @test trr ≈ rrt end @@ -76,7 +76,7 @@ const BMO = BeamletOptics @test r[2] ≈ -sqrt(2) / 2 @test tr ≈ r @test rr ≈ t - @test trt ≈ rrr + @test trt ≈ -rrr @test trr ≈ rrt end end diff --git a/test/E2E/TestMichelson.jl b/test/E2E/TestMichelson.jl index 9aaaed33c..1d8f4e073 100644 --- a/test/E2E/TestMichelson.jl +++ b/test/E2E/TestMichelson.jl @@ -94,10 +94,10 @@ const mm = 1e-3 for (j, y) in enumerate(ys) for (i, x) in enumerate(xs) r = sqrt(x^2 + y^2) - screen[i, j] += BMO.electric_field( + screen[i, j] += -BMO.electric_field( r, short_arm, E0, w0, λ, M2) screen[i, j] += BMO.electric_field( - r, long_arm, E0, w0, λ, M2) * exp(im * pi) + r, long_arm, E0, w0, λ, M2) end end diff --git a/test/Lenses/TestSphericalLenses.jl b/test/Lenses/TestSphericalLenses.jl index b595b6bbf..64c964bf0 100644 --- a/test/Lenses/TestSphericalLenses.jl +++ b/test/Lenses/TestSphericalLenses.jl @@ -144,6 +144,15 @@ const mm = 1e-3 @test test_doublet(707e-9, 143.68mm, 0) @test test_doublet(1064e-9, 143.68mm, +7.466e-4) end + + @testset "AsphericalDoubletLens and Default Refractive Index Fallback" begin + lens = SphericalLens(50e-3, -50e-3, 5e-3, 25e-3, 1.5) + @test BMO.refractive_index(lens)(589e-9) ≈ 1.5 atol=1e-6 + + asph_doublet = AsphericalDoubletLens(50e-3, -50e-3, -100e-3, 5e-3, 3e-3, 25e-3, 1.5, 1.6; k1=0.1, k2=-0.1, k3=0.0) + @test asph_doublet isa DoubletLens + @test BMO.thickness(asph_doublet) ≈ 8e-3 atol=1e-6 + end end end # MODULE \ No newline at end of file diff --git a/test/TestMisc.jl b/test/TestMisc.jl index 0188d1a59..aafb7556f 100644 --- a/test/TestMisc.jl +++ b/test/TestMisc.jl @@ -20,5 +20,5 @@ end @eval Aqua.test_all($BMO; ambiguities = false) end end - -end \ No newline at end of file + +end diff --git a/test/runtests.jl b/test/runtests.jl index a79d9c3d6..2bcde6abb 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -32,6 +32,9 @@ include(joinpath(@__DIR__, "Components", "TestDetectorUtils.jl")) include(joinpath(@__DIR__, "Components", "TestDetector.jl")) include(joinpath(@__DIR__, "Components", "TestBeamsplitters.jl")) include(joinpath(@__DIR__, "Components", "TestPolarizers.jl")) +include(joinpath(@__DIR__, "Components", "TestPolarizingBeamsplitters.jl")) +include(joinpath(@__DIR__, "Components", "TestCoatings.jl")) +include(joinpath(@__DIR__, "Components", "TestBulkAbsorption.jl")) # Test end-to-end models include(joinpath(@__DIR__, "E2E", "TestDoubleGaussLens.jl")) From f8f37387be69a9b0d1993025e9c8e671d10f8ec5 Mon Sep 17 00:00:00 2001 From: "Kliebisch, Oliver" Date: Wed, 19 Aug 2026 07:54:51 +0200 Subject: [PATCH 7/7] fix(physics): apply admittance factor to Fresnel power transmittance and preserve Gaussian beamlet ray weights --- .../Coatings/BoundaryPhysics.jl | 4 ++-- src/OpticalComponents/Coatings/Models.jl | 19 +++++++++++++++---- test/Components/TestCoatings.jl | 13 +++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/OpticalComponents/Coatings/BoundaryPhysics.jl b/src/OpticalComponents/Coatings/BoundaryPhysics.jl index 774c3da39..e0135462d 100644 --- a/src/OpticalComponents/Coatings/BoundaryPhysics.jl +++ b/src/OpticalComponents/Coatings/BoundaryPhysics.jl @@ -336,7 +336,7 @@ function _propagate_splitting_gaussian_beamlet( _, att_field = bulk_attenuation_factor(n_incident, λ, length(c_ray)) # Spawn transmitted - chief_t = Beam(Ray{T}(pos, c_dir_t, nothing, λ, n_transmitted)) + chief_t = Beam(Ray{T}(pos, c_dir_t, nothing, λ, n_transmitted, weight(c_ray))) waist_t = Beam(Ray{T}( position(w_ray) + length(w_ray) * direction(w_ray), w_dir_t, nothing, λ, n_transmitted)) divergent_t = Beam(Ray{T}( @@ -351,7 +351,7 @@ function _propagate_splitting_gaussian_beamlet( t = GaussianBeamlet(chief_t, waist_t, divergent_t, wavelength(gauss), w0_t, E0_t) # Spawn reflected - chief_r = Beam(Ray{T}(pos, c_dir_r, nothing, λ, n_incident)) + chief_r = Beam(Ray{T}(pos, c_dir_r, nothing, λ, n_incident, weight(c_ray))) waist_r = Beam(Ray{T}( position(w_ray) + length(w_ray) * direction(w_ray), w_dir_r, nothing, λ, n_incident)) divergent_r = Beam(Ray{T}( diff --git a/src/OpticalComponents/Coatings/Models.jl b/src/OpticalComponents/Coatings/Models.jl index 41ab94cdc..8f9d8a5d1 100644 --- a/src/OpticalComponents/Coatings/Models.jl +++ b/src/OpticalComponents/Coatings/Models.jl @@ -230,11 +230,19 @@ Compute the average power reflectance from a Jones reflection matrix for unpolar @inline unpolarized_reflectance(J) = 0.5 * (abs2(J[1, 1]) + abs2(J[1, 2]) + abs2(J[2, 1]) + abs2(J[2, 2])) """ - unpolarized_transmittance(J) + unpolarized_transmittance(J, n1=1.0, n2=1.0, θi=0.0) -Compute the average power transmittance from a Jones transmission matrix for unpolarized light. +Compute the average power transmittance from a Jones transmission matrix `J` for unpolarized light, +accounting for the medium admittance ratio `Re(n2*cosθt) / Re(n1*cosθi)`. """ -@inline unpolarized_transmittance(J) = 0.5 * (abs2(J[1, 1]) + abs2(J[1, 2]) + abs2(J[2, 1]) + abs2(J[2, 2])) +@inline function unpolarized_transmittance(J, n1::Number = 1.0, n2::Number = 1.0, θi::Real = 0.0) + sinθt2 = (n1 / n2)^2 * sin(θi)^2 + cosθt = sqrt(Complex(1.0 - sinθt2)) + cosθi = cos(θi) + denom = real(n1 * cosθi) + factor = denom > 0 ? max(0.0, real(n2 * cosθt) / denom) : 1.0 + return factor * 0.5 * (abs2(J[1, 1]) + abs2(J[1, 2]) + abs2(J[2, 1]) + abs2(J[2, 2])) +end """ coating_reflectance(coating, θi, λ, n1, n2; from_front=true, local_p=nothing) @@ -253,7 +261,7 @@ Compute the unpolarized power transmittance T ∈ [0, 1] of a coating model at a """ function coating_transmittance(c, θi, λ, n1, n2; from_front::Bool = true, local_p = nothing) J_t = get_jones_matrix(c, θi, λ, n1, n2, false; from_front = from_front, local_p = local_p) - return clamp(unpolarized_transmittance(J_t), 0.0, 1.0) + return clamp(unpolarized_transmittance(J_t, n1, n2, θi), 0.0, 1.0) end # Shared implementation for simplified constant-reflectance coating models @@ -279,6 +287,9 @@ function get_jones_matrix( end end +coating_reflectance(c::SimpleReflectanceCoating, θi, λ, n1, n2; from_front::Bool = true, local_p = nothing) = c.R +coating_transmittance(c::SimpleReflectanceCoating, θi, λ, n1, n2; from_front::Bool = true, local_p = nothing) = 1.0 - c.R + fresnel_coefficients(c::SimpleBeamsplitterCoating, θi, λ, n1, n2) = (c.rs, c.rp, c.ts, c.tp) function get_jones_matrix(c::SimpleBeamsplitterCoating, θi, λ, n1, n2, is_reflected; from_front::Bool = true, local_p = nothing) diff --git a/test/Components/TestCoatings.jl b/test/Components/TestCoatings.jl index b1c65f619..b0926f3d5 100644 --- a/test/Components/TestCoatings.jl +++ b/test/Components/TestCoatings.jl @@ -605,6 +605,19 @@ const BMO = BeamletOptics @test R≈0.01 atol=1e-6 @test T≈0.99 atol=1e-6 @test R + T≈1.0 atol=1e-6 + + # Uncoated interface (Fresnel field coefficients -> power conversion) + unc = Uncoated() + R_unc = coating_reflectance(unc, 0.0, 1064e-9, 1.0, 1.5) + T_unc = coating_transmittance(unc, 0.0, 1064e-9, 1.0, 1.5) + @test R_unc ≈ 0.04 atol=1e-6 + @test T_unc ≈ 0.96 atol=1e-6 + @test R_unc + T_unc ≈ 1.0 atol=1e-6 + + # Oblique angle (30 deg) + R_30 = coating_reflectance(unc, π/6, 1064e-9, 1.0, 1.5) + T_30 = coating_transmittance(unc, π/6, 1064e-9, 1.0, 1.5) + @test R_30 + T_30 ≈ 1.0 atol=1e-6 end @testset "Analytic Normals and Surface Tags" begin