diff --git a/AGENTS.md b/AGENTS.md index 4b9fd0149..c6b6c4ac0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,7 +113,7 @@ with every release, so it must describe exactly that release. - [test/TestAgentSkill.jl](test/TestAgentSkill.jl) catches mechanical drift only. It fails if the export table in `API.md` differs from `names(BeamletOptics)`, if `metadata.beamletoptics-version` in `SKILL.md` differs from the major.minor version in - `Project.toml`, if `install_agent_skill` breaks, or if a headless template (01–06) throws. + `Project.toml`, if `install_agent_skill` breaks, or if a headless template (all but `07_render_system.jl`) throws. Passing tests do not show that the skill is correct: a changed meaning, e.g. a flipped sign convention, still runs. Checking that is the author's job (above). - On a minor version bump, review the whole skill and update both the version field and the diff --git a/docs/src/api/api.md b/docs/src/api/api.md index bb6a0a8ba..d36ea1036 100644 --- a/docs/src/api/api.md +++ b/docs/src/api/api.md @@ -12,4 +12,4 @@ Depth = 2 ## Public API for dependent packages -Besides the exported names, a few names are declared `public` in `src/Exports.jl` without being exported, e.g. `BeamletOptics.is_static`, `BeamletOptics.hit_count`, the progress interface `BeamletOptics.ProgressSink`, the sampling of the sources `BeamletOptics.AbstractSampling`, the optional `BeamletOptics.bounding_sphere_of` of a shape (see [Bounding sphere pretest](@ref)), or `BeamletOptics.relaunch!` and the beamlet hit records (`BeamletOptics.AstigmaticGaussianBeamletHit(agb, id)`, `BeamletOptics.beamlet_hit_field`) for components that re-emit light, e.g. solvers coupled through a field (see [Re-emitting components](@ref)). Packages built on BMO, such as [BeamletOpticsGUI](https://github.com/StackEnjoyer/BeamletOpticsGUI.jl), may rely on them like on the exported API; other unexported names are internal and may change in any release. Whether a name is public can be checked with `Base.ispublic(BeamletOptics, name)`. Their docstrings are listed in the [Reference](@ref), the render handle protocol is described on the [Live rendering](@ref "Render handle protocol") page. A new `AbstractObject` subtype can add a method of [`properties`](@ref) to list its own parameters, see [Inspecting components](@ref). +Besides the exported names, a few names are declared `public` in `src/Exports.jl` without being exported, e.g. `BeamletOptics.is_static`, `BeamletOptics.hit_count`, the progress interface `BeamletOptics.ProgressSink`, the sampling of the sources `BeamletOptics.AbstractSampling`, the optional `BeamletOptics.bounding_sphere_of` of a shape (see [Bounding sphere pretest](@ref)), `BeamletOptics.AbstractObjectGroup` for own assembly types of separate parts (see [Assemblies: group or multi-shape object](@ref)), or `BeamletOptics.relaunch!` and the beamlet hit records (`BeamletOptics.AstigmaticGaussianBeamletHit(agb, id)`, `BeamletOptics.beamlet_hit_field`) for components that re-emit light, e.g. solvers coupled through a field (see [Re-emitting components](@ref)). Packages built on BMO, such as [BeamletOpticsGUI](https://github.com/StackEnjoyer/BeamletOpticsGUI.jl), may rely on them like on the exported API; other unexported names are internal and may change in any release. Whether a name is public can be checked with `Base.ispublic(BeamletOptics, name)`. Their docstrings are listed in the [Reference](@ref), the render handle protocol is described on the [Live rendering](@ref "Render handle protocol") page. A new `AbstractObject` subtype can add a method of [`properties`](@ref) to list its own parameters, see [Inspecting components](@ref). diff --git a/docs/src/api/geometry.md b/docs/src/api/geometry.md index 4c540d317..d2ba93b64 100644 --- a/docs/src/api/geometry.md +++ b/docs/src/api/geometry.md @@ -47,6 +47,8 @@ BeamletOptics.AbstractObject An `AbstractObject` can consist of multiple `AbstractShape`s or even multiple subsidiary `AbstractObject`s, facilitating the creation of composite optical elements. For example, a lens with an anti-reflective coating could be represented as the substrate and a separate model for the coating, each with its own geometric and optical properties. In general, an `object` can have the `SingleShape` or a `MultiShape` trait. The [`BeamletOptics.AbstractShapeTrait`](@ref) allows the solver and kinematic API to apply different implementations of basis functions via multiple dispatch. +The solver treats a `MultiShape` object as one optical element: whichever of its parts a ray hits, [`BeamletOptics.interact3d`](@ref) is called for the object, which must find that part, e.g. via `shape(intersection(ray))`, and forward the beam to it. This is meant for parts that interact as one, e.g. the prisms and the coating of a [`CubeBeamsplitter`](@ref) or the lenses of a [`DoubletLens`](@ref), which hand the ray on to each other with a [`BeamletOptics.Hint`](@ref). Parts that are separate and interact on their own belong in an [`ObjectGroup`](@ref) or an own subtype of [`BeamletOptics.AbstractObjectGroup`](@ref) instead, see [Assemblies: group or multi-shape object](@ref). + ```@docs; canonical=false BeamletOptics.SingleShape BeamletOptics.MultiShape diff --git a/docs/src/api/kinematics_api.md b/docs/src/api/kinematics_api.md index b26f7f33e..a7e43f9bf 100644 --- a/docs/src/api/kinematics_api.md +++ b/docs/src/api/kinematics_api.md @@ -56,4 +56,5 @@ The primitives `translate3d!(::Movable, x, offset)` and `rotate3d!(::Movable, x, - [`BeamletOptics.AbstractObject`](@ref): the primitives forward to the [`BeamletOptics.AbstractShapeTrait`](@ref) of the object, see [`BeamletOptics.SingleShape`](@ref) and [`BeamletOptics.MultiShape`](@ref) - [`BeamletOptics.AbstractRay`](@ref): only subtypes carrying direction-dependent data (e.g. the field vector of a [`PolarizedRay`](@ref)) need their own `rotate3d!` - [`BeamletOptics.AbstractBeam`](@ref): either implement `_component_beams` or the two primitives; every move resets the beam via `empty!` +- [`BeamletOptics.AbstractObjectGroup`](@ref): moves all members of `objects(group)` rigidly about the group `center` - [`BeamletOptics.AbstractBeamGroup`](@ref): moves its `beams` rigidly about the group `center` diff --git a/docs/src/basics/kinematics/objects.md b/docs/src/basics/kinematics/objects.md index c85c5066a..8e8a82eec 100644 --- a/docs/src/basics/kinematics/objects.md +++ b/docs/src/basics/kinematics/objects.md @@ -20,5 +20,16 @@ For the easier representation of a group of [`BeamletOptics.AbstractObject`](@re ```@docs; canonical=false ObjectGroup -set_pivot3d!(::ObjectGroup, ::Any) +set_pivot3d!(::BeamletOptics.AbstractObjectGroup, ::Any) ``` + +## Assemblies: group or multi-shape object + +An assembly such as a telescope, a periscope or an interferometer arm can be modeled in two ways, and the choice follows from whether its parts touch: + +| Parts of the assembly | Model | `interact3d` | +|---|---|---| +| separate, with air between them | an [`ObjectGroup`](@ref) or an own subtype of [`BeamletOptics.AbstractObjectGroup`](@ref) | none: each part is traced and interacts on its own | +| touching and interacting as one, e.g. cemented or with a shared face | an [`BeamletOptics.AbstractObject`](@ref) with the [`BeamletOptics.MultiShape`](@ref) trait, like the [`CubeBeamsplitter`](@ref) | required: the solver hands every hit to the object, which forwards it to the part that was hit | + +The solver can find out by itself which of several separate parts a ray hits next. Parts that touch need a [`BeamletOptics.Hint`](@ref) across their shared face, which only the component knows. An own subtype of `AbstractObjectGroup` adds named parts and an own constructor to a group and needs no `interact3d` method; its fields and its constructor check are listed in the docstring of [`BeamletOptics.AbstractObjectGroup`](@ref), and the agent skill has a complete example in `templates/08_custom_group.jl`. A `MultiShape` object without an `interact3d` method stops every ray that hits it, with the warning `No interact3d method defined for the MultiShape object`. diff --git a/docs/src/basics/systems.md b/docs/src/basics/systems.md index 1791aa2b8..318868725 100644 --- a/docs/src/basics/systems.md +++ b/docs/src/basics/systems.md @@ -30,10 +30,10 @@ popat!(system, 1) # removes the first top-level object and returns i A [`StaticSystem`](@ref) can not be changed. ```@docs; canonical=false -Base.push!(::System, ::Vararg{BeamletOptics.AbstractObject}) +Base.push!(::System, ::Vararg{BeamletOptics.ObjectOrGroup}) Base.pop!(::System) Base.popat!(::System, ::Integer) -Base.delete!(::System, ::BeamletOptics.AbstractObject) +Base.delete!(::System, ::BeamletOptics.ObjectOrGroup) ``` ## Solving systems diff --git a/docs/src/basics/visualization/components.md b/docs/src/basics/visualization/components.md index 26a7b59b6..4b5faf925 100644 --- a/docs/src/basics/visualization/components.md +++ b/docs/src/basics/visualization/components.md @@ -4,10 +4,11 @@ Optical components are rendered by drawing their shape. Example renderings of th ## Components -The generic method below covers every [`BeamletOptics.AbstractObject`](@ref), including groups of components such as an [`ObjectGroup`](@ref), whose members are rendered one after another. +The generic methods below cover every [`BeamletOptics.AbstractObject`](@ref) and every group of components such as an [`ObjectGroup`](@ref), whose members are rendered one after another. ```@docs render!(::Union{GLMakie.Axis3, GLMakie.LScene}, ::BeamletOptics.AbstractObject) +render!(::Union{GLMakie.Axis3, GLMakie.LScene}, ::BeamletOptics.AbstractObjectGroup) ``` ### Materials diff --git a/docs/src/basics/visualization/live_rendering.md b/docs/src/basics/visualization/live_rendering.md index c3e4d3e72..8e5ab2b73 100644 --- a/docs/src/basics/visualization/live_rendering.md +++ b/docs/src/basics/visualization/live_rendering.md @@ -65,8 +65,8 @@ An object that is added to a system at runtime, see [Changing a system](@ref), i handle of the system, and removed from it again, by: ```@docs; canonical=false -BeamletOptics.live_render!(::BeamletOptics.AbstractSystemRenderHandle, ::BeamletOptics.AbstractObject) -BeamletOptics.remove_render!(::BeamletOptics.AbstractSystemRenderHandle, ::BeamletOptics.AbstractObject) +BeamletOptics.live_render!(::BeamletOptics.AbstractSystemRenderHandle, ::BeamletOptics.ObjectOrGroup) +BeamletOptics.remove_render!(::BeamletOptics.AbstractSystemRenderHandle, ::BeamletOptics.ObjectOrGroup) ``` ```julia diff --git a/ext/RenderBoundingSphere.jl b/ext/RenderBoundingSphere.jl index 23db39b01..3064ec6d6 100644 --- a/ext/RenderBoundingSphere.jl +++ b/ext/RenderBoundingSphere.jl @@ -50,11 +50,18 @@ render_bounding_sphere!(ax::_RenderEnv, ::BMO.SingleShape, obj; kwargs...) = # The solver tests the parts one by one, hence one sphere per part, and the main sphere of the object # first, which is drawn in `main_color` -function render_bounding_sphere!(ax::_RenderEnv, ::BMO.MultiShape, obj; main_color = :orange, kwargs...) - for part in BMO.shape(obj) +render_bounding_sphere!(ax::_RenderEnv, ::BMO.MultiShape, obj; kwargs...) = + _render_part_spheres!(ax, obj, BMO.shape(obj); kwargs...) + +# An object group: the spheres of its objects, then the main sphere of the group +render_bounding_sphere!(ax::_RenderEnv, group::BMO.AbstractObjectGroup; kwargs...) = + _render_part_spheres!(ax, group, BMO.objects(group); kwargs...) + +function _render_part_spheres!(ax::_RenderEnv, whole, parts; main_color = :orange, kwargs...) + for part in parts render_bounding_sphere!(ax, part; main_color, kwargs...) end - render_bounding_sphere!(ax, BMO.bounding_sphere_of(obj); kwargs..., color = main_color) + render_bounding_sphere!(ax, BMO.bounding_sphere_of(whole); kwargs..., color = main_color) return nothing end diff --git a/ext/RenderCamera.jl b/ext/RenderCamera.jl index 30512520c..fd3bd0430 100644 --- a/ext/RenderCamera.jl +++ b/ext/RenderCamera.jl @@ -63,7 +63,7 @@ function render_lcs!( return nothing end -function render_lcs!(ax::LScene, object::BMO.AbstractObject; scale::Real = 10, show_labels::Bool = false) +function render_lcs!(ax::LScene, object::BMO.ObjectOrGroup; scale::Real = 10, show_labels::Bool = false) render_lcs!(ax, BMO.position(object), BMO.orientation(object); scale, show_labels) return nothing end diff --git a/ext/RenderLive.jl b/ext/RenderLive.jl index 1905c85e0..d0aa2a191 100644 --- a/ext/RenderLive.jl +++ b/ext/RenderLive.jl @@ -7,8 +7,8 @@ Live rendering of objects and systems, see the render handle protocol in `src/Re """ ObjectRenderHandle <: AbstractObjectRenderHandle -Live rendering handle of an `AbstractObject`, see [`live_render!`](@ref), or of anything with a pose -that is drawn by a function, see `live_render!(draw, ax, x)`. +Live rendering handle of an `AbstractObject` or an object group, see [`live_render!`](@ref), or of +anything with a pose that is drawn by a function, see `live_render!(draw, ax, x)`. The plots are generated once by the `draw` function in the reference pose `P0`, `R0` of the object. Afterwards, the rigid transformation from the reference pose to the current pose is applied as the @@ -23,7 +23,7 @@ mutable struct ObjectRenderHandle{O} <: AbstractObjectRenderHandle # reference pose P0::Point3{Float64} R0::Matrix{Float64} - # reference poses of the MultiShape subparts + # reference poses of the subparts, see `_rigid_parts` subP0::Vector{Point3{Float64}} subR0::Vector{Matrix{Float64}} # last rendered pose @@ -50,11 +50,21 @@ function _direction_frame(d) return hcat(x, y, cross(x, y)) end -function _subposes(obj) - (obj isa BMO.AbstractObject && BMO.shape_trait_of(obj) isa BMO.MultiShape) || - return Point3{Float64}[], Matrix{Float64}[] - parts = BMO.shape(obj) - return [_pose(p)[1] for p in parts], [_pose(p)[2] for p in parts] +""" + _rigid_parts(x) + +Returns the subparts of `x` that can be moved on their own, i.e. the parts of a `MultiShape` object +or the objects of an object group. Anything else has none. +""" +_rigid_parts(::Any) = () +_rigid_parts(obj::BMO.AbstractObject) = _rigid_parts(BMO.shape_trait_of(obj), obj) +_rigid_parts(::BMO.AbstractShapeTrait, obj) = () +_rigid_parts(::BMO.MultiShape, obj) = BMO.shape(obj) +_rigid_parts(group::BMO.AbstractObjectGroup) = BMO.objects(group) + +function _subposes(x) + parts = _rigid_parts(x) + return Point3{Float64}[_pose(p)[1] for p in parts], Matrix{Float64}[_pose(p)[2] for p in parts] end """Returns the plots that are added to the `ax` by `f()`.""" @@ -74,6 +84,17 @@ function live_render!(ax::_RenderEnv, obj::BMO.AbstractObject; kwargs...) return live_render!(() -> render!(ax, obj; kwargs...), ax, obj) end +""" + live_render!(ax, group::AbstractObjectGroup; kwargs...) + +Renders the `group` via [`render!`](@ref) and returns one `ObjectRenderHandle` for the whole group. +If an object of the group is moved on its own, the group is rendered again by +[`update_render!`](@ref). +""" +function live_render!(ax::_RenderEnv, group::BMO.AbstractObjectGroup; kwargs...) + return live_render!(() -> render!(ax, group; kwargs...), ax, group) +end + """ live_render!(draw, ax, x) @@ -125,11 +146,12 @@ end """ _is_rigid(h::ObjectRenderHandle; atol = 1e-6, rtol = 1e-6) -Checks if all subparts of a `MultiShape` object still match a rigid motion of the whole object. +Checks if all subparts of a `MultiShape` object or of an object group still match a rigid motion +of the whole. """ function _is_rigid(h::ObjectRenderHandle; atol = 1e-6, rtol = 1e-6) isempty(h.subP0) && return true - parts = BMO.shape(h.obj) + parts = _rigid_parts(h.obj) length(parts) != length(h.subP0) && return false P, R = _pose(h.obj) Rd = R * h.R0' @@ -155,8 +177,8 @@ end """ update_render!(h::ObjectRenderHandle) -Applies the current pose of the object to its plots. If the subparts of a `MultiShape` object have -not been moved rigidly, the object is rendered again. +Applies the current pose of the object to its plots. If the subparts of a `MultiShape` object or of +an object group have not been moved rigidly, the object is rendered again. """ function update_render!(h::ObjectRenderHandle) # The pose of a MultiShape object is the pose of its first part, hence check the other parts first @@ -210,7 +232,7 @@ mutable struct SystemRenderHandle{S <: BMO.AbstractSystem} <: AbstractSystemRend ax::_RenderEnv sys::S handles::Vector{AbstractObjectRenderHandle} - parent::IdDict{BMO.AbstractObject, BMO.AbstractObject} + parent::IdDict{BMO.ObjectOrGroup, BMO.AbstractObjectGroup} end function Base.show(io::IO, h::SystemRenderHandle) @@ -241,7 +263,7 @@ object, such that each object of a group can be moved on its own without renderi """ function live_render!(ax::_RenderEnv, sys::BMO.AbstractSystem; kwargs...) handles = AbstractObjectRenderHandle[] - parent = IdDict{BMO.AbstractObject, BMO.AbstractObject}() + parent = IdDict{BMO.ObjectOrGroup, BMO.AbstractObjectGroup}() # Avoid use of objects(sys), which flattens the groups foreach(obj -> _live_render_leaves!(handles, parent, ax, obj; kwargs...), sys.objects) return SystemRenderHandle(ax, sys, handles, parent) @@ -257,7 +279,7 @@ function _live_render_leaves!(handles, parent, ax::_RenderEnv, obj::BMO.Abstract end function _live_render_leaves!(handles, parent, ax::_RenderEnv, group::BMO.AbstractObjectGroup; kwargs...) - for child in BMO.shape(group) + for child in BMO.objects(group) parent[child] = group _live_render_leaves!(handles, parent, ax, child; kwargs...) end @@ -265,13 +287,13 @@ function _live_render_leaves!(handles, parent, ax::_RenderEnv, group::BMO.Abstra end """ - live_render!(h::SystemRenderHandle, obj::AbstractObject; kwargs...) + live_render!(h::SystemRenderHandle, obj; kwargs...) -Live-renders `obj` into the axis of `h` and adds its object handles to `h`, see -[`live_render!`](@ref). Returns the new object handles. If an object of `obj` can not be rendered, +Live-renders `obj`, an object or object group, into the axis of `h` and adds its object handles to +`h`, see [`live_render!`](@ref). Returns the new object handles. If an object of `obj` can not be rendered, `h` and its axis are left as they were. """ -function live_render!(h::SystemRenderHandle, obj::BMO.AbstractObject; kwargs...) +function live_render!(h::SystemRenderHandle, obj::BMO.ObjectOrGroup; kwargs...) for leaf in BMO.Leaves(obj) any(oh -> rendered(oh) === leaf, h.handles) && throw(ArgumentError( "the $(nameof(typeof(leaf))) is already rendered by the system handle")) @@ -291,8 +313,8 @@ function live_render!(h::SystemRenderHandle, obj::BMO.AbstractObject; kwargs...) end # Also forgets the hierarchy of the groups of `obj` -function remove_render!(h::SystemRenderHandle, obj::BMO.AbstractObject) - invoke(remove_render!, Tuple{AbstractSystemRenderHandle, BMO.AbstractObject}, h, obj) +function remove_render!(h::SystemRenderHandle, obj::BMO.ObjectOrGroup) + invoke(remove_render!, Tuple{AbstractSystemRenderHandle, BMO.ObjectOrGroup}, h, obj) foreach(o -> delete!(h.parent, o), BMO.PreOrderDFS(obj)) return nothing end diff --git a/ext/RenderObjects.jl b/ext/RenderObjects.jl index fae153e37..5419c1cc0 100644 --- a/ext/RenderObjects.jl +++ b/ext/RenderObjects.jl @@ -45,6 +45,21 @@ for each `object`. """ render!(ax::_RenderEnv, object::BMO.AbstractObject; kwargs...) = _render!(ax, object; kwargs...) +""" + render!(ax, group::AbstractObjectGroup; edges = nothing, show_bounding_sphere = false, kwargs...) + +Renders all objects of the `group`, merged like the parts of a `MultiShape` object, see +`_render_parts!`. Nested groups are merged into the meshes of the outermost group. The `kwargs`, +e.g. `material` or `color`, and an explicit `edges` apply to all objects. `show_bounding_sphere` +is consumed by the outermost group, which draws the spheres of all its objects, see +[`render_bounding_sphere!`](@ref). +""" +function render!(ax::_RenderEnv, group::BMO.AbstractObjectGroup; show_bounding_sphere::Bool = false, kwargs...) + _render_parts!(ax, BMO.objects(group); kwargs...) + show_bounding_sphere && render_bounding_sphere!(ax, group) + return nothing +end + # Dispatch helper fct. for RenderPolarizers.jl, do not remove. # Consumes `show_bounding_sphere`: the trait methods and the parts of a `MultiShape` object never see # the keyword, the outermost object draws the spheres of all its parts. @@ -93,22 +108,30 @@ class and the look, see `_default_edges`, i.e. mechanics parts have no edges. Ne parts are merged into the meshes of the outermost object. The `kwargs`, e.g. `material` or `color`, and an explicit `edges` apply to all parts. """ -function render!(ax::_RenderEnv, ::BMO.MultiShape, obj; edges::Union{Nothing, Bool} = nothing, - kwargs...) +render!(ax::_RenderEnv, ::BMO.MultiShape, obj; kwargs...) = _render_parts!(ax, BMO.shape(obj); kwargs...) + +""" + _render_parts!(ax, parts; edges = nothing, kwargs...) + +Renders the `parts` of a `MultiShape` object or the objects of an object group and merges their +analytic meshes, see `render!(ax, ::MultiShape, obj)`. Within an enclosing call the meshes are +left to the collector of the outermost one. +""" +function _render_parts!(ax::_RenderEnv, parts; edges::Union{Nothing, Bool} = nothing, kwargs...) kw = isnothing(edges) ? kwargs : (; kwargs..., edges) if !isnothing(_MESH_COLLECTOR[]) - for _obj in BMO.shape(obj) - render!(ax, _obj; kw...) + for part in parts + render!(ax, part; kw...) end return nothing end - parts = Any[] - with(_MESH_COLLECTOR => parts) do - for _obj in BMO.shape(obj) - render!(ax, _obj; kw...) + collected = Any[] + with(_MESH_COLLECTOR => collected) do + for part in parts + render!(ax, part; kw...) end end - _plot_collected!(ax, parts) + _plot_collected!(ax, collected) return nothing end diff --git a/skills/beamletoptics/CHECKLIST.md b/skills/beamletoptics/CHECKLIST.md index dbe632e49..336cbfa4b 100644 --- a/skills/beamletoptics/CHECKLIST.md +++ b/skills/beamletoptics/CHECKLIST.md @@ -50,3 +50,7 @@ 13. **Moving a child beam is not allowed**; move the source (this also resets its trace). 14. **Rendering**: `flen` defaults to 1 m for rays; camera helpers need an `LScene`; GLMakie needs a display (`xvfb-run -a` on headless Linux). Without OpenGL, fall back to CairoMakie (`Axis3` only). +15. **An assembly of separate parts is a group**, not a `MultiShape` object: a `MultiShape` wrapper + without `interact3d` stops every ray that hits it. Use `ObjectGroup` or a subtype of + `BeamletOptics.AbstractObjectGroup` (`templates/08_custom_group.jl`); only parts that touch and + interact as one get a `MultiShape` type with `interact3d` (`components/systems-and-groups.md`). diff --git a/skills/beamletoptics/README.md b/skills/beamletoptics/README.md index a097b2ce4..575841ecc 100644 --- a/skills/beamletoptics/README.md +++ b/skills/beamletoptics/README.md @@ -30,8 +30,8 @@ The canonical entry point is `SKILL.md`. ## Templates -The files in `templates/` are small, complete scripts. Templates 01 to 06 run headless with only -BeamletOptics installed. `07_render_system.jl` additionally needs `GLMakie` and a display +The files in `templates/` are small, complete scripts. All templates except `07_render_system.jl` +run headless with only BeamletOptics installed. `07_render_system.jl` additionally needs `GLMakie` and a display (`xvfb-run -a` on headless Linux). Paths below are relative to this skill directory; `` is a Julia project that has BeamletOptics @@ -39,11 +39,11 @@ Paths below are relative to this skill directory; `` is a Julia project tha ```sh julia --project= templates/03_psf_airy.jl -julia --project= scripts/run_templates.jl # smoke-test 01-06 +julia --project= scripts/run_templates.jl # smoke-test the headless templates julia --project= scripts/run_templates.jl --render # all templates, needs GLMakie ``` -From the root of the BeamletOptics repository, use the package env (templates 01 to 06) or the docs +From the root of the BeamletOptics repository, use the package env (headless templates) or the docs env (all templates): ```sh diff --git a/skills/beamletoptics/SKILL.md b/skills/beamletoptics/SKILL.md index e6555cdc9..1cb8c604e 100644 --- a/skills/beamletoptics/SKILL.md +++ b/skills/beamletoptics/SKILL.md @@ -53,7 +53,9 @@ When this Skill is active: place with `translate3d!`/`translate_to3d!`. Rotations pivot about `position(obj)`, so for a single object the order of rotate/translate does not matter; pass a `pivot` to `rotate3d!` to rotate about another point. - Stack lenses along +y using `thickness(lens)`. -- Group rigid sub-assemblies with `ObjectGroup` (see `components/systems-and-groups.md`). +- Group rigid sub-assemblies with `ObjectGroup` or an own subtype of `BeamletOptics.AbstractObjectGroup`; + only parts that touch and interact as one form a `MultiShape` object with its own `interact3d` + (see "Assemblies" in `components/systems-and-groups.md`). 4) Solve - `system = System([obj1, obj2, ...])` (order does not matter, tracing is non-sequential); diff --git a/skills/beamletoptics/components/systems-and-groups.md b/skills/beamletoptics/components/systems-and-groups.md index 6f7dc5717..9f69a89cb 100644 --- a/skills/beamletoptics/components/systems-and-groups.md +++ b/skills/beamletoptics/components/systems-and-groups.md @@ -38,6 +38,9 @@ tracing has run for `get_progress_threshold()` s (default 5 s). group = ObjectGroup([lens1, lens2, mount]) # members may be objects or other groups ``` +- An `ObjectGroup` is a kinematic container: each member is traced and interacts on its own. Read + the members with `BeamletOptics.objects(group)`. A component whose parts interact as one (e.g. a + cemented doublet) is an `AbstractObject` subtype with the `MultiShape` trait. - `position(group)` is the group `center`. It starts at the **origin**, not at the centroid; `orientation(group)` starts as identity. - `translate3d!(group, Δ)` moves all members and the center. @@ -53,3 +56,23 @@ periscope = ObjectGroup([m1, m2]) set_pivot3d!(periscope, [0, 0, 50mm]) zrotate3d!(periscope, deg2rad(10)) ``` + +## Assemblies: group or one multi-shape object + +Decide by whether the parts touch: + +| Parts of the assembly | Use | `interact3d` | +|---|---|---| +| separate, with air between them (telescope, periscope, lens group, arm with mounts) | `ObjectGroup`, or an own subtype of `BeamletOptics.AbstractObjectGroup` | none: each part interacts on its own | +| touching and interacting as one (cemented, a `Hint` across a shared face, a shared medium) | an `AbstractObject` subtype with `shape_trait_of(::T) = MultiShape()` | required, for every beam model it must support | + +- An own group type gives named parts and an own constructor. It needs the fields `objects`, + `center::Point3{T}` and `dir::SMatrix{3,3,T,9}`, is a `mutable struct`, and its constructor + checks `allequal(BeamletOptics.is_static, objects)`. Moving, `set_pivot3d!`, systems and rendering + work as for an `ObjectGroup`. See `templates/08_custom_group.jl`. +- Never wrap separate parts in a `MultiShape` object without `interact3d`: the solver hands every + hit to the wrapper, finds no method, warns `No interact3d method defined` and stops the ray. +- A `MultiShape` object finds the part that was hit via `shape(intersection(ray))` and forwards to + it (see `CubeBeamsplitter`, `DoubletLens`). Beamlets reach this ray method through their generic + `interact3d(system, obj, beamlet, id::Int)`, once per ray of the beamlet. If a part has its own + beamlet method (detectors, beamsplitters), the object needs a beamlet method that forwards to it. diff --git a/skills/beamletoptics/scripts/run_templates.jl b/skills/beamletoptics/scripts/run_templates.jl index a2737f711..e2958161c 100644 --- a/skills/beamletoptics/scripts/run_templates.jl +++ b/skills/beamletoptics/scripts/run_templates.jl @@ -1,4 +1,4 @@ -# Smoke-test the headless templates (01-06) against the active BeamletOptics environment. +# Smoke-test the headless templates (all but 07) against the active BeamletOptics environment. # # julia --project= scripts/run_templates.jl # diff --git a/skills/beamletoptics/templates/08_custom_group.jl b/skills/beamletoptics/templates/08_custom_group.jl new file mode 100644 index 000000000..065734bd7 --- /dev/null +++ b/skills/beamletoptics/templates/08_custom_group.jl @@ -0,0 +1,53 @@ +# An own assembly type: a periscope with named mirrors that moves and traces like an ObjectGroup. +# Its mirrors do not touch, so each one interacts on its own and the type needs no interact3d. +# Parts that touch and interact as one (cemented, a Hint across a shared face) need an +# AbstractObject with the MultiShape trait and its own interact3d instead, like CubeBeamsplitter. +using BeamletOptics +using LinearAlgebra: I +const BMO = BeamletOptics + +const mm = 1e-3 + +# A subtype of AbstractObjectGroup needs the fields `objects`, `center` (pivot) and `dir` +# (orientation). It is mutable, since moving the group changes `center` and `dir`. +mutable struct Periscope{T, L, U} <: BMO.AbstractObjectGroup{T} + center::BMO.Point3{T} + dir::BMO.SMatrix{3, 3, T, 9} + const objects::Tuple{L, U} +end + +# Named parts +lower_mirror(p::Periscope) = p.objects[1] +upper_mirror(p::Periscope) = p.objects[2] + +# Built along +y: the lower mirror folds +y -> +z, the upper one +z -> +y, `height` above it +function Periscope(height::Real; diameter::Real = 25.4mm) + lower = RoundPlanoMirror(diameter, 6mm) + xrotate3d!(lower, deg2rad(-45)) + upper = RoundPlanoMirror(diameter, 6mm) + xrotate3d!(upper, deg2rad(135)) + translate3d!(upper, [0, 0, height]) + objects = (lower, upper) + # the members of a group are either all static or all movable + allequal(BMO.is_static, objects) || throw(ArgumentError("mixed static and movable parts")) + # pivot halfway up, frame of the global axes + return Periscope(BMO.Point3(0.0, 0.0, height / 2), BMO.SMatrix{3, 3}(1.0I), objects) +end + +periscope = Periscope(100mm) +translate3d!(periscope, [0, 50mm, 0]) # moves both mirrors and the pivot + +det = Detector(20mm) +translate3d!(det, [0, 250mm, 100mm]) + +system = System([periscope, det]) # a group is flattened, each mirror is traced on its own +beam = Beam([0, 0, 0], [0, 1, 0], 633e-9) +solve_system!(system, beam) +println("upper mirror at ", position(upper_mirror(periscope)), ", ", + length(rays(beam)), " ray segments") + +# Turn the whole periscope about its pivot and trace again: the parallel mirrors keep the +# beam direction (+y), only the beam position on the detector changes +zrotate3d!(periscope, deg2rad(2)) +solve_system!(system, beam; initialize = true) +println("after the turn: end direction ", direction(last(rays(beam)))) diff --git a/src/AbstractTypes/AbstractBoundingSphere.jl b/src/AbstractTypes/AbstractBoundingSphere.jl index 38baf5f09..26c2b9e13 100644 --- a/src/AbstractTypes/AbstractBoundingSphere.jl +++ b/src/AbstractTypes/AbstractBoundingSphere.jl @@ -153,8 +153,9 @@ SingleBoundingSphere(::AbstractShape, sphere::NoBoundingSphere) = sphere """ bounding_sphere_of(shape::AbstractShape) bounding_sphere_of(object::AbstractObject) + bounding_sphere_of(group::AbstractObjectGroup) -Computes a sphere that encloses the `shape` or `object` in its current pose and returns it as a +Computes a sphere that encloses the `shape`, `object` or `group` in its current pose and returns it as a [`SingleBoundingSphere`](@ref) or [`MultiBoundingSphere`](@ref), or returns [`NoBoundingSphere`](@ref)`()` if there is none. @@ -194,6 +195,8 @@ function bounding_sphere_of(::MultiShape, object::AbstractObject) return MultiBoundingSphere(map(bounding_sphere_of, shape(object))) end +bounding_sphere_of(group::AbstractObjectGroup) = MultiBoundingSphere(map(bounding_sphere_of, objects(group))) + """ bounding_box(sphere::AbstractBoundingSphere) @@ -286,6 +289,11 @@ function _register!(table::BoundingSphereTable, ::MultiShape, object::AbstractOb return _store!(table, object, MultiBoundingSphere(parts)) end +function _register!(table::BoundingSphereTable, group::AbstractObjectGroup) + parts = map(part -> _register!(table, part), objects(group)) + return _store!(table, group, MultiBoundingSphere(parts)) +end + # Center and radius of the `sphere` as the table holds them: as `Float64`, with the radius enlarged # by the rounding of the pose and the parameters of the shape in its own number type function _table_values(sphere::AbstractBoundingSphere) diff --git a/src/AbstractTypes/AbstractObject.jl b/src/AbstractTypes/AbstractObject.jl index edea8b07f..670ffd21c 100644 --- a/src/AbstractTypes/AbstractObject.jl +++ b/src/AbstractTypes/AbstractObject.jl @@ -85,7 +85,7 @@ E.g. for a custom multi-shape object the user of this API needs to define: `BeamletOptics.shape(obj::MyObject) = (obj.front, obj.back)` !!! warning - Whenever your object consists of nested structures (e.g. [`ObjectGroup`](@ref)s or other [`MultiShape`](@ref)s) + Whenever your object consists of nested structures (e.g. other [`MultiShape`](@ref)s) it is the responsibility of the user to ensure that **each atomic shape, i.e. `SingleShape`, is only listed once**. Failure to ensure this can lead to spurious behaviour when using the kinematic API. """ @@ -115,32 +115,3 @@ orientation!(object::AbstractObject, dir) = orientation!(shape_trait_of(object), translate3d!(::Movable, object::AbstractObject, offset) = translate3d!(shape_trait_of(object), object, offset) rotate3d!(::Movable, object::AbstractObject, R::AbstractMatrix) = rotate3d!(shape_trait_of(object), object, R) - -""" - AbstractObjectGroup <: AbstractObject - -Container type for groups of optical elements, based on a tree-like data structure. Intended for easier kinematic handling of connected elements. -See also [`ObjectGroup`](@ref) for a concrete implementation. - -# Implementation reqs. - -Subtypes of `AbstractObjectGroup` must implement the following: - -## Fields: - -- `objects`: stores objects or additional subgroups of objects, allows for hierarchical structures - -## Functions: - -- for the kinematic API, all corresponding functions of [`AbstractObject`](@ref) must be implemented -""" -abstract type AbstractObjectGroup{T} <: AbstractObject{T} end - -AbstractTrees.children(group::AbstractObjectGroup) = group.objects - -function initialize!(group::AbstractObjectGroup) - for object in AbstractTrees.children(group) - initialize!(object) - end - return nothing -end diff --git a/src/AbstractTypes/AbstractObjectGroup.jl b/src/AbstractTypes/AbstractObjectGroup.jl new file mode 100644 index 000000000..97330cefd --- /dev/null +++ b/src/AbstractTypes/AbstractObjectGroup.jl @@ -0,0 +1,121 @@ +""" + AbstractObjectGroup + +Container type for groups of optical elements, based on a tree-like data structure. Intended for easier kinematic handling of connected elements. +See also [`ObjectGroup`](@ref) for a concrete implementation. + +A ray or beam interacts with the object of the group that it hits. A component whose parts interact +as one, e.g. a cemented doublet, is an [`AbstractObject`](@ref) with the [`MultiShape`](@ref) trait. + +!!! tip "Own assembly types" + An assembly of separate parts, e.g. a telescope from its mirrors, can be a subtype of + `AbstractObjectGroup` with named parts and its own constructor: it needs the fields below and + no `interact3d` method, and the kinematic API, [`set_pivot3d!`](@ref), systems and rendering + work as for an [`ObjectGroup`](@ref). See `templates/08_custom_group.jl` of the agent skill. + +# Implementation reqs. + +Subtypes of `AbstractObjectGroup` must implement the following: + +## Fields: + +- `objects`: a tuple of [`AbstractObject`](@ref)s or additional subgroups, allows for hierarchical structures +- `center`: a `Point3{T}` which is regarded as the reference origin (pivot) of the group +- `dir`: a `SMatrix{3,3,T,9}` that describes the local coordinate system of the group + +Since the kinematic API modifies `center` and `dir`, the subtype must be a `mutable struct`. + +## Functions: + +If the fields above do not exist, the following getters/setters must be dispatched: + +- [`objects`](@ref): getter for the `objects` field or equivalent return type +- `position` / `position!`: gets or sets the reference origin (pivot) +- [`orientation`](@ref) / `orientation!`: gets or sets the orientation matrix + +## Kinematic + +An `AbstractObjectGroup` is a container: it takes the kinematic class of its `objects`, i.e. +[`BeamletOptics.Movable`](@ref) with an [`BeamletOptics.Oriented`](@ref) frame for movable objects, see +[`BeamletOptics.AbstractKinematicTrait`](@ref). The constructors must check that the `objects` are either +all static or all movable, e.g. with `allequal(BeamletOptics.is_static, objects)`. The primitives `translate3d!(::Movable, group, offset)` and +`rotate3d!(::Movable, group, R::AbstractMatrix)` move all `objects` and the pose of the group. +""" +abstract type AbstractObjectGroup{T} end + +""" + ObjectOrGroup + +Union of [`AbstractObject`](@ref) and [`AbstractObjectGroup`](@ref): what a [`System`](@ref) or a +group stores and what [`render!`](@ref) draws. +""" +const ObjectOrGroup = Union{AbstractObject, AbstractObjectGroup} + +""" + objects(group::AbstractObjectGroup) + +Exposes all objects/subgroups stored within the group. +""" +objects(group::AbstractObjectGroup) = group.objects + +AbstractTrees.children(group::AbstractObjectGroup) = objects(group) + +kinematic_trait_of(group::AbstractObjectGroup) = _container_trait(objects(group)) + +Base.position(group::AbstractObjectGroup) = group.center +position!(group::AbstractObjectGroup{T}, pos) where {T} = (group.center = Point3{T}(pos)) + +orientation(group::AbstractObjectGroup) = group.dir +orientation!(group::AbstractObjectGroup{T}, dir) where {T} = (group.dir = SMatrix{3, 3, T, 9}(dir)) + +function initialize!(group::AbstractObjectGroup) + foreach(initialize!, objects(group)) + return nothing +end + +""" + set_pivot3d!(group::AbstractObjectGroup, pivot) + +Moves the kinematic pivot (`center`) of `group` to `pivot`, without moving any of its +`objects`. The pivot is the reference point used by [`rotate3d!`](@ref), +[`translate_to3d!`](@ref) and [`reset_translation3d!`](@ref); the group [`orientation`](@ref) +is unchanged. + +# Example + +Rotate a lens group about its first surface instead of the group's default center: + +```julia +group = ObjectGroup([lens1, lens2]) +set_pivot3d!(group, position(lens1)) +rotate3d!(group, [0, 0, 1], deg2rad(5)) # rotates about lens1's position, not the old center +``` +""" +function set_pivot3d!(group::AbstractObjectGroup, pivot) + position!(group, pivot) + return nothing +end + +""" + translate3d!(::Movable, group::AbstractObjectGroup, offset) + +Moves all objects of the `group` and its `center` by `offset`. +""" +function translate3d!(::Movable, group::AbstractObjectGroup, offset) + position!(group, position(group) .+ offset) + foreach(member -> translate3d!(member, offset), objects(group)) + return nothing +end + +""" + rotate3d!(::Movable, group::AbstractObjectGroup, R::AbstractMatrix) + +Rotates all objects of the `group` by `R` about the group `center` and updates the group +[`orientation`](@ref) to `R * orientation(group)`. +""" +function rotate3d!(::Movable, group::AbstractObjectGroup, R::AbstractMatrix) + orientation!(group, R * orientation(group)) + pivot = position(group) + foreach(member -> rotate3d!(member, R, pivot), objects(group)) + return nothing +end diff --git a/src/AbstractTypes/AbstractRay.jl b/src/AbstractTypes/AbstractRay.jl index 1ea6d85c0..70de6c51c 100644 --- a/src/AbstractTypes/AbstractRay.jl +++ b/src/AbstractTypes/AbstractRay.jl @@ -195,7 +195,7 @@ function intersect3d(::MultiShape, object::AbstractObject, ray::AbstractRay) end """ - intersect3d(::MultiShape, group::AbstractObjectGroup, ray::AbstractRay) + intersect3d(group::AbstractObjectGroup, ray::AbstractRay) Returns the closest intersection of the `ray` with the objects of the `group`. In contrast to a [`MultiShape`](@ref) object, the intersection keeps the object of the group that was hit, since @@ -203,8 +203,8 @@ this object, not the group, interacts with the ray. No object is tested if the r bounding sphere of the group, which the table of a running solve holds, see `bounding_sphere_of(table, x)`. """ -function intersect3d(::MultiShape, group::AbstractObjectGroup, ray::AbstractRay) - return intersect3d(bounding_sphere_of(current_bounding_spheres(), group), shape(group), ray) +function intersect3d(group::AbstractObjectGroup, ray::AbstractRay) + return intersect3d(bounding_sphere_of(current_bounding_spheres(), group), objects(group), ray) end """ diff --git a/src/AbstractTypes/AbstractSystem.jl b/src/AbstractTypes/AbstractSystem.jl index 6842c8100..f29e50824 100644 --- a/src/AbstractTypes/AbstractSystem.jl +++ b/src/AbstractTypes/AbstractSystem.jl @@ -26,12 +26,28 @@ refractive_index(::AbstractSystem, λ::Real) = 1.0 Defines the optical interaction between an incoming/outgoing beam/ray of light and an optical element, must return an [`AbstractInteraction`](@ref) or `nothing`. The default behavior is that no interaction occurs, i.e. return of `nothing`, which should stop the system tracing procedure. Refer to the [`AbstractInteraction`](@ref) typedocs for more information on the return type value. + +A [`MultiShape`](@ref) object receives this call for whichever of its parts was hit. Its method +finds that part, e.g. via `shape(intersection(ray))`, and hands the beam to it, see +[`CubeBeamsplitter`](@ref). Parts that do not interact as one belong in an +[`ObjectGroup`](@ref) or another [`AbstractObjectGroup`](@ref) instead, where each part +interacts on its own. """ -function interact3d(::AbstractSystem, ::ObjectType, ::AbstractBeam, ::RayType) where {ObjectType<:AbstractObject, RayType<:AbstractRay} - @warn lazy"No interact3d method defined for:" ObjectType RayType +function interact3d(::AbstractSystem, object::AbstractObject, ::AbstractBeam, ray::AbstractRay) + _warn_no_interact3d(shape_trait_of(object), object, ray) return nothing end +# Warning of the fallback above; for a multi-shape object it names both ways to fix it +_warn_no_interact3d(::AbstractShapeTrait, object, ray) = + @warn lazy"No interact3d method defined for:" ObjectType = typeof(object) RayType = typeof(ray) +_warn_no_interact3d(::MultiShape, object, ray) = @warn lazy""" + No interact3d method defined for the MultiShape object $(nameof(typeof(object))). + If its parts interact as one (e.g. cemented, with a Hint across a shared face), define + interact3d and hand the beam to the part that was hit, like CubeBeamsplitter. + If its parts interact on their own, make it an ObjectGroup or a subtype of + AbstractObjectGroup, which needs no interact3d.""" RayType = typeof(ray) + """ Hint diff --git a/src/AbstractTypes/AbstractTypes.jl b/src/AbstractTypes/AbstractTypes.jl index 72cdd9b89..a9a36f348 100644 --- a/src/AbstractTypes/AbstractTypes.jl +++ b/src/AbstractTypes/AbstractTypes.jl @@ -8,7 +8,7 @@ Types: AbstractRefractiveOptic AbstractDetector AbstractBeamsplitter - AbstractObjectGroup + AbstractObjectGroup AbstractRay AbstractBeam AbstractSystem @@ -35,6 +35,7 @@ Base.Experimental.@max_methods 1 function intersect3d end include("AbstractKinematicTrait.jl") include("AbstractShape.jl") include("AbstractObject.jl") +include("AbstractObjectGroup.jl") include("AbstractShapeTrait.jl") include("AbstractRay.jl") include("AbstractBeam.jl") diff --git a/src/Exports.jl b/src/Exports.jl index b1ec26a1d..d25b0c03e 100644 --- a/src/Exports.jl +++ b/src/Exports.jl @@ -85,6 +85,8 @@ public is_static, hit_count, wavelength, min_num_rays, ProgressSink, PROGRESS_SI public relaunch!, beamlet_hit_field, GaussianBeamletHit, AstigmaticGaussianBeamletHit # optional part of the shape interface, see AbstractShape public bounding_sphere_of, AbstractBoundingSphere, NoBoundingSphere, SingleBoundingSphere, MultiBoundingSphere +# own assembly types of separate parts, see AbstractObjectGroup +public AbstractObjectGroup # element type of path_segments public PathSegment public AbstractSampling, NoSampling, DiscRings, DiscSunflower, DiscLine, ConeRings, ConeSunflower, diff --git a/src/ObjectGroups.jl b/src/ObjectGroups.jl index 9639c0932..5c609a33e 100644 --- a/src/ObjectGroups.jl +++ b/src/ObjectGroups.jl @@ -10,9 +10,11 @@ Main purpose is handling of, i.e., groups of lenses. - `dir`: a 3x3 matrix that describes the common `orientation` of the group - `objects`: stores [`AbstractObject`](@ref), can also store subgroups of type [`AbstractObjectGroup`](@ref) +Each of its `objects` is traced and interacts on its own, read them via [`objects`](@ref)`(group)`. + ## Kinematic -A `ObjectGroup` implements the kinematic functions of [`AbstractObject`](@ref). The following logic is applied to +An `ObjectGroup` implements the kinematic API, see [`BeamletOptics.AbstractKinematicTrait`](@ref). The following logic is applied to - [`translate3d!`](@ref): all objects in the group are translated by the offset vector - [`translate_to3d!`](@ref): all objects are moved in parallel such that the group `center` is equal to the target position @@ -22,58 +24,16 @@ A `ObjectGroup` implements the kinematic functions of [`AbstractObject`](@ref). The `objects` must be either all static or all movable, otherwise the constructor throws an `ArgumentError`. The group takes that kinematic class, see [`BeamletOptics.AbstractKinematicTrait`](@ref). """ -mutable struct ObjectGroup{T, O <: Tuple{Vararg{AbstractObject}}} <: AbstractObjectGroup{T} +mutable struct ObjectGroup{T, O <: Tuple{Vararg{ObjectOrGroup}}} <: AbstractObjectGroup{T} dir::SMatrix{3, 3, T, 9} center::Point3{T} const objects::O end -shape_trait_of(::ObjectGroup) = MultiShape() - -kinematic_trait_of(g::ObjectGroup) = _container_trait(objects(g)) - -shape(o::ObjectGroup) = o.objects - -Base.position(group::ObjectGroup) = group.center -position!(group::ObjectGroup, pos) = (group.center = pos) - -orientation(group::ObjectGroup) = group.dir -orientation!(group::ObjectGroup, dir) = (group.dir = dir) - -""" - set_pivot3d!(group::ObjectGroup, pivot) - -Moves the kinematic pivot (`center`) of `group` to `pivot`, without moving any of its -`objects`. The pivot is the reference point used by [`rotate3d!`](@ref), -[`translate_to3d!`](@ref) and [`reset_translation3d!`](@ref); the group [`orientation`](@ref) -is unchanged. - -# Example - -Rotate a lens group about its first surface instead of the group's default center: - -```julia -group = ObjectGroup([lens1, lens2]) -set_pivot3d!(group, position(lens1)) -rotate3d!(group, [0, 0, 1], deg2rad(5)) # rotates about lens1's position, not the old center -``` -""" -function set_pivot3d!(group::ObjectGroup{T}, pivot) where {T} - position!(group, Point3{T}(pivot)) - return nothing -end - ObjectGroup(v::AbstractArray, T = Float64) = ObjectGroup(tuple(v...), T) function ObjectGroup(v::V, T = Float64) where {V <: Tuple} _check_kinematic_members(v) ObjectGroup{T, V}(SMatrix{3,3}(one(T)*I), Point3{T}(0), v) end -""" - objects(group::ObjectGroup) - -Exposes all objects/subgroups stored within the group. -""" -objects(group::ObjectGroup) = group.objects - Base.show(::IO, ::MIME"text/plain", group::ObjectGroup) = print_tree(group) diff --git a/src/Properties.jl b/src/Properties.jl index 383f52f7f..75d42ebaf 100644 --- a/src/Properties.jl +++ b/src/Properties.jl @@ -62,6 +62,7 @@ Returns the properties that [`properties`](@ref) lists for any `x`, see its conv - for an [`AbstractObject`](@ref), depending on its [`BeamletOptics.AbstractShapeTrait`](@ref): the [`properties`](@ref) of its shape (`"Shape"` and the stored dimensions, e.g. `"Diameter [m]"`) or the number of its `"Parts"` +- for an object group: the number of its objects as `"Parts"` Methods of `properties` for specific types start from this list, see [`properties`](@ref). """ @@ -70,9 +71,12 @@ default_properties(x) = Pair{String, Any}["Type" => _type_name(x); default_prope default_properties(x::AbstractObject) = Pair{String, Any}["Type" => _type_name(x); default_properties(kinematic_trait_of(x), x); default_properties(shape_trait_of(x), x)] +default_properties(x::AbstractObjectGroup) = Pair{String, Any}["Type" => _type_name(x); + default_properties(kinematic_trait_of(x), x); "Parts" => length(objects(x))] + # Pose by the kinematic trait default_properties(::Static, _) = Pair{String, Any}[] -default_properties(::Static, x::AbstractObject) = Pair{String, Any}["Position [m]" => _vector(position(x))] +default_properties(::Static, x::ObjectOrGroup) = Pair{String, Any}["Position [m]" => _vector(position(x))] default_properties(::Movable{Oriented}, x) = Pair{String, Any}["Position [m]" => _vector(position(x)), "Optical axis" => _vector(direction(x))] default_properties(::Movable{Directed}, x) = Pair{String, Any}["Position [m]" => _vector(position(x)), diff --git a/src/Render/RenderBoundingSphere.jl b/src/Render/RenderBoundingSphere.jl index 8cbc16370..1bc689c98 100644 --- a/src/Render/RenderBoundingSphere.jl +++ b/src/Render/RenderBoundingSphere.jl @@ -18,10 +18,12 @@ be tight. [`NoBoundingSphere`](@ref) gives no plot - shape: one plot, or none if the shape has no bounding sphere - object: the sphere of its shape, or, if it consists of several parts (e.g. a doublet lens, a cube - beamsplitter or an `ObjectGroup`), the sphere of each part, since the solver tests each part on its + beamsplitter), the sphere of each part, since the solver tests each part on its own, and the main sphere around all parts in `main_color`. The solver tests a ray against the main sphere first. An object without a main sphere, because a part has none, gets none. An object without a sphere, e.g. a `NonInteractableObject`, gets no plot. +- object group (`ObjectGroup`): like an object of several parts, the spheres of its objects and then + the main sphere of the group - system: the spheres of all its objects # Keyword args @@ -45,5 +47,5 @@ render!(ax, system; show_bounding_sphere = true) If no suitable backend is loaded, a [`MissingBackendError`](@ref) will be thrown. """ -render_bounding_sphere!(::Any, ::Union{AbstractBoundingSphere, AbstractShape, AbstractObject, AbstractSystem}; kwargs...) = +render_bounding_sphere!(::Any, ::Union{AbstractBoundingSphere, AbstractShape, ObjectOrGroup, AbstractSystem}; kwargs...) = throw(MissingBackendError()) diff --git a/src/Render/RenderCamera.jl b/src/Render/RenderCamera.jl index d2c83115a..e1b5f03e4 100644 --- a/src/Render/RenderCamera.jl +++ b/src/Render/RenderCamera.jl @@ -68,11 +68,12 @@ look_at!(::Any, ::AbstractVector, ::AbstractVector; kwargs...) = throw(MissingBa render_lcs!(ax, pos, lcs; scale = 10, show_labels = false) render_lcs!(ax, object; scale = 10, show_labels = false) -Draws the local coordinate system of an object (or of an explicit `pos`/orientation pair) -into `ax` as a red/green/yellow arrow triad, if a suitable backend is loaded. Useful to +Draws the local coordinate system of an object or object group (or of an explicit +`pos`/orientation pair) into `ax` as a red/green/yellow arrow triad, if a suitable backend is +loaded. Useful to make the reference frame of an imported CAD mesh visible in the scene. If no suitable backend is loaded, a [`MissingBackendError`](@ref) will be thrown. """ render_lcs!(::Any, ::AbstractArray = zeros(3), ::AbstractMatrix = Matrix{Float64}(I, 3, 3); kwargs...) = throw(MissingBackendError()) -render_lcs!(::Any, ::AbstractObject; kwargs...) = throw(MissingBackendError()) +render_lcs!(::Any, ::ObjectOrGroup; kwargs...) = throw(MissingBackendError()) diff --git a/src/Render/RenderHandles.jl b/src/Render/RenderHandles.jl index 38750eb48..659fd92f8 100644 --- a/src/Render/RenderHandles.jl +++ b/src/Render/RenderHandles.jl @@ -31,8 +31,8 @@ abstract type AbstractRenderHandle end """ AbstractObjectRenderHandle <: AbstractRenderHandle -Handle of one movable thing, returned by `live_render!(ax, obj)` for an `AbstractObject` and by -`live_render!(draw, ax, x)` for anything with a pose. The plots are drawn once; +Handle of one movable thing, returned by `live_render!(ax, obj)` for an `AbstractObject` or an +object group and by `live_render!(draw, ax, x)` for anything with a pose. The plots are drawn once; [`update_render!`](@ref) applies the current pose of [`rendered`](@ref)`(h)` as their model matrix (and draws them again if the parts of a `MultiShape` object moved relative to each other). [`pick_object`](@ref) returns `rendered(h)` for the plots of [`pickable_plots`](@ref). diff --git a/src/Render/RenderLive.jl b/src/Render/RenderLive.jl index 756dc25ce..db132c9d1 100644 --- a/src/Render/RenderLive.jl +++ b/src/Render/RenderLive.jl @@ -40,10 +40,11 @@ If no suitable backend is loaded, a [`MissingBackendError`](@ref) will be thrown live_render!(::Function, ::Any, ::Any) = throw(MissingBackendError()) """ - live_render!(h::AbstractSystemRenderHandle, obj::AbstractObject; kwargs...) -> Vector{<:AbstractObjectRenderHandle} + live_render!(h::AbstractSystemRenderHandle, obj; kwargs...) -> Vector{<:AbstractObjectRenderHandle} -Live-renders `obj` into the axis of the system handle `h` and adds it to `h`, e.g. an object that -was added to the system via `push!(system, obj)` after `h` was created. An object group is rendered +Live-renders `obj`, an object or object group, into the axis of the system handle `h` and adds it +to `h`, e.g. an object that was added to the system via `push!(system, obj)` after `h` was created. +An object group is rendered per object, with its hierarchy known to [`render_parent`](@ref), like the groups of `live_render!(ax, system)`. Returns the new object handles, one per rendered object. The system of `h` is not changed. An `obj` that `h` already renders throws an `ArgumentError`. @@ -52,7 +53,7 @@ Keyword arguments are passed on as for [`render!`](@ref). Implemented by the han `live_render!(ax, system)`. A system handle that does not implement it throws an `ArgumentError`: render `obj` via `live_render!(ax, obj)` and add its handle via `push!(h, oh)` instead. """ -function live_render!(h::AbstractSystemRenderHandle, ::AbstractObject; kwargs...) +function live_render!(h::AbstractSystemRenderHandle, ::ObjectOrGroup; kwargs...) throw(ArgumentError( "a $(nameof(typeof(h))) can not render objects, use live_render!(ax, obj) and push!(h, oh) instead")) end @@ -88,15 +89,15 @@ function remove_render!(h::AbstractSystemRenderHandle) end """ - remove_render!(h::AbstractSystemRenderHandle, obj::AbstractObject) + remove_render!(h::AbstractSystemRenderHandle, obj) -Removes `obj` from the system handle `h`: deletes the plots of `obj` (of all objects of an object -group) from the axis and removes their object handles from `h`, e.g. after `delete!(system, obj)`. +Removes `obj`, an object or object group, from the system handle `h`: deletes the plots of `obj` +(of all objects of an object group) from the axis and removes their object handles from `h`, e.g. after `delete!(system, obj)`. The system of `h` is not changed. Nothing happens for an `obj` that `h` does not render. An object within a group can not be removed on its own and throws an `ArgumentError`: remove the group instead. """ -function remove_render!(h::AbstractSystemRenderHandle, obj::AbstractObject) +function remove_render!(h::AbstractSystemRenderHandle, obj::ObjectOrGroup) parent = render_parent(h, obj) isnothing(parent) || throw(ArgumentError( "the $(nameof(typeof(obj))) is part of a $(nameof(typeof(parent))) of the system handle, remove the group instead")) diff --git a/src/System.jl b/src/System.jl index 713a92fd9..1e7a42d9d 100644 --- a/src/System.jl +++ b/src/System.jl @@ -5,22 +5,23 @@ A container storing the optical elements of, i.e. a camera lens or lab setup. # Fields -- `objects`: vector containing the different objects that are part of the system (subtypes of [`AbstractObject`](@ref)). +- `objects`: vector containing the different objects (subtypes of [`AbstractObject`](@ref)) and object groups + (subtypes of [`AbstractObjectGroup`](@ref)) that are part of the system. The constructor copies the vector it is given, such that `push!` and `delete!` of the system do not change it. """ struct System <: AbstractSystem - objects::Vector{AbstractObject} - System(objects::AbstractVector) = new(collect(AbstractObject, objects)) + objects::Vector{ObjectOrGroup} + System(objects::AbstractVector) = new(collect(ObjectOrGroup, objects)) end -System(object::AbstractObject) = System([object]) +System(object::ObjectOrGroup) = System([object]) """ System() Creates an empty system, to which objects are added via `push!`. """ -System() = System(AbstractObject[]) +System() = System(ObjectOrGroup[]) # `Leaves` of an empty vector is the vector itself, which is no object """ @@ -35,7 +36,7 @@ objects(system::System) = isempty(system.objects) ? () : Leaves(system.objects) _is_leaf_of(obj, leaves) = any(leaf -> leaf === obj, leaves) """ - push!(system::System, objects::AbstractObject...) -> system + push!(system::System, objects::ObjectOrGroup...) -> system Adds the `objects` (or object groups) at the top level of the `system`, such that they are traced by the following calls of [`solve_system!`](@ref). An object that is already part of the `system`, @@ -44,7 +45,7 @@ directly or within a group, throws an `ArgumentError`; in this case nothing is a Beams and beam groups that were solved before do not know the new object: solve them again with `solve_system!(system, beam)`. The `system` must not be changed while it is being solved. """ -function Base.push!(system::System, objs::AbstractObject...) +function Base.push!(system::System, objs::ObjectOrGroup...) leaves = AbstractObject[o for o in objects(system)] for obj in objs, leaf in Leaves(obj) _is_leaf_of(leaf, leaves) && throw(ArgumentError( @@ -56,7 +57,7 @@ function Base.push!(system::System, objs::AbstractObject...) end """ - pop!(system::System) -> AbstractObject + pop!(system::System) -> ObjectOrGroup Removes the last top-level object (or object group) of the `system` and returns it. Beams that were solved before must be solved again, see `delete!(system, object)`. @@ -64,7 +65,7 @@ were solved before must be solved again, see `delete!(system, object)`. Base.pop!(system::System) = pop!(system.objects) """ - popat!(system::System, i::Integer) -> AbstractObject + popat!(system::System, i::Integer) -> ObjectOrGroup Removes the `i`-th top-level object (or object group) of the `system` and returns it. The index counts the objects and groups as they were added, a group counts as one. An index out of bounds @@ -74,7 +75,7 @@ throws a `BoundsError`. Beams that were solved before must be solved again, see Base.popat!(system::System, i::Integer) = popat!(system.objects, i) """ - delete!(system::System, object::AbstractObject) -> system + delete!(system::System, object::ObjectOrGroup) -> system Removes the top-level `object` (or object group) from the `system`, compared by identity. Nothing happens for an `object` that is not part of the `system`. An object within a group can not be @@ -83,7 +84,7 @@ removed on its own and throws an `ArgumentError`: remove the group instead. Beams and beam groups that were solved before still end on the removed object: solve them again with `solve_system!(system, beam)`. The `system` must not be changed while it is being solved. """ -function Base.delete!(system::System, obj::AbstractObject) +function Base.delete!(system::System, obj::ObjectOrGroup) i = findfirst(o -> o === obj, system.objects) if isnothing(i) for top in system.objects @@ -114,9 +115,9 @@ can be added or removed after construction but it allows for more performant ray struct StaticSystem{T <: Tuple} <: AbstractSystem objects::T end -StaticSystem(object::AbstractObject) = StaticSystem((object)) -StaticSystem(object::AbstractObjectGroup) = StaticSystem([object]) -function StaticSystem(objects::AbstractArray{<:AbstractObject}) +StaticSystem(object::ObjectOrGroup) = StaticSystem([object]) +# No bound on the element type: a vector of objects and groups has the element type `Any` +function StaticSystem(objects::AbstractArray) StaticSystem(tuple(collect(Leaves(objects))...)) end @@ -468,12 +469,7 @@ function solve_system!( return nothing end -function AbstractTrees.printnode(io::IO, node::B; kw...) where {B <: AbstractObject} - show(io, node) -end -function AbstractTrees.printnode(io::IO, - node::B; - kw...) where {B <: AbstractObjectGroup} +function AbstractTrees.printnode(io::IO, node::ObjectOrGroup; kw...) show(io, node) end diff --git a/test/Geometry/TestBoundingSphere.jl b/test/Geometry/TestBoundingSphere.jl index 42e73215b..928528277 100644 --- a/test/Geometry/TestBoundingSphere.jl +++ b/test/Geometry/TestBoundingSphere.jl @@ -172,10 +172,11 @@ sphere_prism(radius, bound = radius) = BMO.Prism(WrappedSDF(BMO.SphereSDF(radius other = sphere_prism(radius) translate3d!(other, [0.2, -0.1, 0.05]) outer = ObjectGroup([inner, other]) - for object in (doublet, cube, inner, outer) + for (object, parts) in ((doublet, BMO.shape(doublet)), (cube, BMO.shape(cube)), + (inner, BMO.objects(inner)), (outer, BMO.objects(outer))) main = BMO.bounding_sphere_of(object) @test main isa BMO.MultiBoundingSphere{Float64} - @test all(part -> encloses(main, BMO.bounding_sphere_of(part)), BMO.shape(object)) + @test all(part -> encloses(main, BMO.bounding_sphere_of(part)), parts) end # tight for two spheres: they touch the sphere around them from within a, b = sphere_prism(radius), sphere_prism(2radius) @@ -201,7 +202,7 @@ sphere_prism(radius, bound = radius) = BMO.Prism(WrappedSDF(BMO.SphereSDF(radius @test table isa BMO.BoundingSphereTable # the shapes of the single-shape objects, and the multi-shape object and the group themselves shapes = [BMO.shape(prism), BMO.shape(doublet.front), BMO.shape(doublet.back), - BMO.shape.(BMO.shape(group))...] + BMO.shape.(BMO.objects(group))...] @test all(s -> haskey(table, s), shapes) @test haskey(table, doublet) && haskey(table, group) @test length(table) == length(shapes) + 2 @@ -210,7 +211,7 @@ sphere_prism(radius, bound = radius) = BMO.Prism(WrappedSDF(BMO.SphereSDF(radius computed = BMO.bounding_sphere_of(prism) @test table[BMO.shape(prism)].pos == computed.pos @test computed.radius < table[BMO.shape(prism)].radius < computed.radius * (1 + 1e-6) - @test encloses(table[group], table[BMO.shape(first(BMO.shape(group)))]) + @test encloses(table[group], table[BMO.shape(first(BMO.objects(group)))]) # the kind of the sphere is kept @test all(s -> table[s] isa BMO.SingleBoundingSphere{Float64}, shapes) @test table[doublet] isa BMO.MultiBoundingSphere{Float64} @@ -349,7 +350,7 @@ sphere_prism(radius, bound = radius) = BMO.Prism(WrappedSDF(BMO.SphereSDF(radius end # also for a group within a group nested = ObjectGroup([ObjectGroup([sphere_prism(radius)]), sphere_prism(radius)]) - @test BMO.object(BMO.intersect3d(nested, ray)) === only(BMO.shape(first(BMO.shape(nested)))) + @test BMO.object(BMO.intersect3d(nested, ray)) === only(BMO.objects(first(BMO.objects(nested)))) end @testset "Same result as without spheres" begin diff --git a/test/Rendering/TestRenderBoundingSphere.jl b/test/Rendering/TestRenderBoundingSphere.jl index 79d4fa2bf..0786f1689 100644 --- a/test/Rendering/TestRenderBoundingSphere.jl +++ b/test/Rendering/TestRenderBoundingSphere.jl @@ -30,6 +30,7 @@ end shapes(obj) = shapes(BMO.shape_trait_of(obj), obj) shapes(::BMO.SingleShape, obj) = Any[BMO.shape(obj)] shapes(::BMO.MultiShape, obj) = reduce(vcat, (shapes(part) for part in BMO.shape(obj)); init = Any[]) +shapes(group::BMO.AbstractObjectGroup) = reduce(vcat, (shapes(part) for part in BMO.objects(group)); init = Any[]) shapes(sys::System) = reduce(vcat, (shapes(obj) for obj in sys.objects); init = Any[]) # The sphere of a shape. While shape types may still return a tuple (center_local, radius), convert it. @@ -51,6 +52,10 @@ function all_spheres(::BMO.MultiShape, obj) parts = reduce(vcat, (all_spheres(part) for part in BMO.shape(obj)); init = Any[]) return push!(parts, BMO.bounding_sphere_of(obj)) end +function all_spheres(group::BMO.AbstractObjectGroup) + parts = reduce(vcat, (all_spheres(part) for part in BMO.objects(group)); init = Any[]) + return push!(parts, BMO.bounding_sphere_of(group)) +end all_spheres(sys::System) = reduce(vcat, (all_spheres(obj) for obj in sys.objects); init = Any[]) """Returns the main spheres of `x` that are drawn: those of objects with several parts, also nested ones.""" @@ -62,6 +67,10 @@ function all_main_spheres(::BMO.MultiShape, obj) parts = reduce(vcat, (all_main_spheres(part) for part in BMO.shape(obj)); init = Any[]) return push!(parts, BMO.bounding_sphere_of(obj)) end +function all_main_spheres(group::BMO.AbstractObjectGroup) + parts = reduce(vcat, (all_main_spheres(part) for part in BMO.objects(group)); init = Any[]) + return push!(parts, BMO.bounding_sphere_of(group)) +end all_main_spheres(sys::System) = reduce(vcat, (all_main_spheres(obj) for obj in sys.objects); init = Any[]) # A shape type without a bounding sphere method diff --git a/test/Rendering/TestRenderLive.jl b/test/Rendering/TestRenderLive.jl index 046d7c7de..9f5fdf373 100644 --- a/test/Rendering/TestRenderLive.jl +++ b/test/Rendering/TestRenderLive.jl @@ -219,6 +219,43 @@ Base.delete!(h::_Combined, oh::BMO.AbstractObjectRenderHandle) = (filter!(c -> c remove_render!(h) end + @testset "Nested AbstractObjectGroup: render! and live_render!" begin + inner = ObjectGroup([RoundPlanoMirror(0.02, 0.004), RoundPlanoMirror(0.02, 0.004)]) + translate3d!(inner.objects[2], [0, 0.05, 0]) + outer = ObjectGroup([RoundPlanoMirror(0.02, 0.004), inner]) + translate3d!(outer.objects[1], [0, 0.1, 0]) + + # render!: the meshes of all objects are merged by the outermost group + ax2 = LScene(Figure()[1, 1]) + n0 = length(ax2.scene.plots) + @test isnothing(render!(ax2, outer)) + rendered = ax2.scene.plots[(n0 + 1):end] + @test count(p -> p isa Makie.Mesh, rendered) == 1 + @test length(rendered) == 1 + Ext._default_edges(:reflective) + + # live_render!: one handle for the whole group with the plots of render! + h = live_render!(ax, outer) + @test h isa Ext.ObjectRenderHandle + @test BMO.rendered(h) === outer + @test map(Makie.plotfunc, h.plots) == map(Makie.plotfunc, rendered) + @test length(h.subP0) == 2 # the mirror and the inner group + + # rigid motion of the outer group: the plots are kept + plots = copy(h.plots) + translate3d!(outer, [0.02, 0, 0]) + zrotate3d!(outer, deg2rad(10)) + update_render!(h) + @test h.plots == plots + + # the inner group moved on its own: rendered again + translate3d!(inner, [0, 0, 0.03]) + update_render!(h) + @test length(h.plots) == length(plots) + @test !any(p -> any(q -> q === p, plots), h.plots) + + remove_render!(h) + end + @testset "System: one handle per object, update & pick" begin sys = System([RoundPlanoMirror(0.025, 0.005), SphericalLens(0.05, -0.05, 0.01, 0.02)]) translate3d!(sys.objects[2], [0.0, 0.15, 0.0]) diff --git a/test/TestAbstractTypes.jl b/test/TestAbstractTypes.jl index c7b9b4635..5fe83459b 100644 --- a/test/TestAbstractTypes.jl +++ b/test/TestAbstractTypes.jl @@ -184,6 +184,15 @@ const BMO = BeamletOptics TestObject() = TestObject(TestShapeless()) + # a wrapper of two objects with the MultiShape trait but without interact3d + struct TestMultiObject{T, A, B} <: BMO.AbstractObject{T} + a::A + b::B + end + TestMultiObject(a::BMO.AbstractObject{T}, b) where {T} = TestMultiObject{T, typeof(a), typeof(b)}(a, b) + BMO.shape_trait_of(::TestMultiObject) = BMO.MultiShape() + BMO.shape(o::TestMultiObject) = (o.a, o.b) + @testset "AbstractObject" begin object = TestObject() @test isa(BMO.shape(object), TestShapeless) @@ -215,6 +224,10 @@ const BMO = BeamletOptics obj, beam, ray)===nothing + # a MultiShape object without interact3d: the warning names both ways to fix it + multi = TestMultiObject(TestObject(), TestObject()) + @test_logs (:warn, r"MultiShape object .*interact3d.*AbstractObjectGroup"s) BMO.interact3d( + sys, multi, beam, ray) === nothing end end end diff --git a/test/TestKinematicTrait.jl b/test/TestKinematicTrait.jl index 411532b34..ae1b15f91 100644 --- a/test/TestKinematicTrait.jl +++ b/test/TestKinematicTrait.jl @@ -262,6 +262,8 @@ end set_pivot3d!(g_static, [1.0, 2.0, 3.0]) @test position(g_static) == [1.0, 2.0, 3.0] @test all(position(o) == zeros(3) for o in BMO.objects(g_static)) + # a static group lists its position like a static object + @test properties(g_static) == ["Type" => "ObjectGroup", "Position [m]" => [1.0, 2.0, 3.0], "Parts" => 2] end @testset "Primitive fallback" begin diff --git a/test/TestObjectGroups.jl b/test/TestObjectGroups.jl index f77e68a87..5e6dc1f74 100644 --- a/test/TestObjectGroups.jl +++ b/test/TestObjectGroups.jl @@ -139,6 +139,18 @@ const BMO = BeamletOptics end end + @testset "Type and members" begin + @test !(BMO.AbstractObjectGroup <: BMO.AbstractObject) + @test !(objects isa BMO.AbstractObject) + @test objects isa BMO.ObjectOrGroup && center isa BMO.ObjectOrGroup + @test !hasmethod(BMO.shape_trait_of, Tuple{typeof(objects)}) + @test !hasmethod(BMO.shape, Tuple{typeof(objects)}) + @test BMO.objects(objects) === (center, circle) + @test collect(AbstractTrees.children(objects)) == [center, circle] + # only objects and groups are members, e.g. no shapes + @test_throws TypeError ObjectGroup([center, BMO.CylinderSDF(1e-3, 2e-3)]) + end + @testset "System compatibility" begin # Test if objects in ObjectGroup are exposed correctly when iterating system = System(objects) diff --git a/test/TestSourceKinematics.jl b/test/TestSourceKinematics.jl index 5917f9630..c8bb86f59 100644 --- a/test/TestSourceKinematics.jl +++ b/test/TestSourceKinematics.jl @@ -514,7 +514,7 @@ start_rays(b) = map(BMO.first_ray, BMO._component_beams(b)) axis = [1.0, -2.0, 0.5] θ = 0.8 # compared state: (position, orientation/direction) for objects, start rays for sources - state(x::Union{BMO.AbstractShape, BMO.AbstractObject}) = (position(x), BMO.orientation(x)) + state(x::Union{BMO.AbstractShape, BMO.ObjectOrGroup}) = (position(x), BMO.orientation(x)) state(r::BMO.AbstractRay) = (position(r), BMO.direction(r)) state(b::BMO.Beam) = state(BMO.first_ray(b)) state(b::BMO.AbstractBeam) = map(c -> state(BMO.first_ray(c)), BMO._component_beams(b)) diff --git a/test/TestSystem.jl b/test/TestSystem.jl index ab4297a12..68dd5ce69 100644 --- a/test/TestSystem.jl +++ b/test/TestSystem.jl @@ -293,6 +293,17 @@ end @test objs == [m1] @test System(objs).objects !== objs + # a vector of objects and groups has the element type `Any` + mixed = [RoundPlanoMirror(25e-3, 5e-3), ObjectGroup([RoundPlanoMirror(25e-3, 5e-3)])] + @test eltype(mixed) === Any + @test System(mixed).objects == mixed + @test StaticSystem(mixed).objects === (mixed[1], only(BMO.objects(mixed[2]))) + @test StaticSystem(mixed[1]).objects === (mixed[1],) + @test StaticSystem(mixed[2]).objects === (only(BMO.objects(mixed[2])),) + # anything else is no part of a system + @test_throws MethodError System([mixed[1], 42]) + @test_throws MethodError push!(System(), 42) + # an empty system exposes no objects and is solved without a hit system = System() @test isempty(system.objects)