Skip to content

Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.

C#

The class is the part's kind: PartKind removed, and the two part menus share their entries

Alexander Graefa82451a70682
diff --git a/OpticalParts.md b/OpticalParts.md
index c1c07f6..87be02d 100644
--- a/OpticalParts.md
+++ b/OpticalParts.md
@@ -128,7 +128,7 @@ Index2 (2.00), Width (int, 200, ≥ 2). Layers stacked along +x', the stack cent
**`GrinLensPart`** — Length (100), Diameter (100), CentreIndex (1.80), EdgeIndex (1.50), Coating (0).
Rectangle Length × Diameter; n(y') = n_c − (n_c − n_e)·(2y'/D)².
-`Project`: `Parts` collection (serialised between `Sources` and `Probes`), `AddPart(PartKind)` using
+`Project`: `Parts` collection (serialised between `Sources` and `Probes`), `AddPart(Type)` and `AddPart<T>()` (the class is the kind; 2026-10-22, the `PartKind` enum removed) using
`NumberedName`, `Duplicate(OpticalPart)`, `Normalize()` over the parts. `ProjectWatcher`: subscribe the parts and
their `Points` lists (`Resubscribe`, the property-change filter list); `ProjectChange.AffectsSimulation` true for a
part, a `PartPoint`, the parts list and `Project.Parts`. `LegacyProject` (Jeroen's `configuration.json`) has no
@@ -177,7 +177,7 @@ IReadOnlyList<OpticalPart> parts)`:
"Part:<name>" and "PartAngle:<name>". The shape itself shows through the glowing outline; drawing the selected
part's outline in the accent colour is a welcome extra if cheap (the painter can expose a polyline per part).
- **Strings**: `TreeParts`, `ToolAddPart`, `TipToolAddPart`, `MenuAddLens` … (five), `Label.`/`Hint.` for every
- member above, `Enum.PartKind.*`, in all four tables. British spelling in the UI.
+ member above, in all four tables. British spelling in the UI.
- **Live editing** rules of `CLAUDE.md` hold: a part edit is a simulation edit.
## Verification
diff --git a/WaveDudeNext.WPF/Commands/ProjectCommands.cs b/WaveDudeNext.WPF/Commands/ProjectCommands.cs
index 06cec4d..ec34929 100644
--- a/WaveDudeNext.WPF/Commands/ProjectCommands.cs
+++ b/WaveDudeNext.WPF/Commands/ProjectCommands.cs
@@ -29,7 +29,7 @@ public static class ProjectCommands
/// <summary>Appends a new source.</summary>
public static readonly RoutedUICommand AddSource = new("Add source", nameof(AddSource), typeof(ProjectCommands));
- /// <summary>Appends a new optical part of the <see cref="WaveDudeNext.Model.PartKind"/> given as parameter; without one, opens the menu of kinds on the invoking element.</summary>
+ /// <summary>Appends a new optical part of the <see cref="WaveDudeNext.Model.OpticalPart"/> subclass given as parameter; without one, opens the menu of kinds on the invoking element.</summary>
public static readonly RoutedUICommand AddPart = new("Add part", nameof(AddPart), typeof(ProjectCommands));
/// <summary>Appends a new probe.</summary>
diff --git a/WaveDudeNext.WPF/MainWindow.Project.cs b/WaveDudeNext.WPF/MainWindow.Project.cs
index a8728ee..b779df4 100644
--- a/WaveDudeNext.WPF/MainWindow.Project.cs
+++ b/WaveDudeNext.WPF/MainWindow.Project.cs
@@ -111,15 +111,15 @@ public partial class MainWindow
private void OnAddSource(object sender, ExecutedRoutedEventArgs e) => Added(Project.AddSource());
/// <summary>
- /// Add part: with a <see cref="PartKind"/> as parameter (the menu entries) the part is appended; without one (the
+ /// Add part: with an <see cref="OpticalPart"/> subclass as parameter (the menu entries) the part is appended; without one (the
/// "+ Part" button, the Parts folder's plus) the invoking element's context menu, the menu of kinds, opens under it,
/// so the kind is chosen there (keyboard: Space opens it, the arrows walk it, Enter picks).
/// </summary>
private void OnAddPart(object sender, ExecutedRoutedEventArgs e)
{
- if (e.Parameter is PartKind kind)
+ if (e.Parameter is Type type)
{
- Added(Project.AddPart(kind));
+ Added(Project.AddPart(type));
}
else
{
diff --git a/WaveDudeNext.WPF/Panes/ProjectTree.xaml b/WaveDudeNext.WPF/Panes/ProjectTree.xaml
index 34d49ab..de64771 100644
--- a/WaveDudeNext.WPF/Panes/ProjectTree.xaml
+++ b/WaveDudeNext.WPF/Panes/ProjectTree.xaml
@@ -81,33 +81,37 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<Setter Property="MinHeight" Value="20" />
<Setter Property="Margin" Value="1,0" />
</Style>
- <!-- the menu of part kinds, the optics first and the plain shapes after a separator: the "+ Part" button and the Parts
- folder's plus open it (AddPart without a parameter opens the invoking element's context menu; each entry adds its
- kind). One instance per button -->
- <ContextMenu x:Key="PartKindMenu" x:Shared="False">
- <ContextMenu.Resources>
- <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
- <Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
- </Style>
- </ContextMenu.Resources>
- <MenuItem Header="{DynamicResource MenuAddLens}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Lens}" AutomationProperties.AutomationId="AddPart:Lens" />
- <MenuItem Header="{DynamicResource MenuAddFiber}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Fiber}" AutomationProperties.AutomationId="AddPart:Fiber" />
- <MenuItem Header="{DynamicResource MenuAddBraggReflector}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.BraggReflector}" AutomationProperties.AutomationId="AddPart:BraggReflector" />
- <MenuItem Header="{DynamicResource MenuAddGrinLens}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.GrinLens}" AutomationProperties.AutomationId="AddPart:GrinLens" />
- <MenuItem Header="{DynamicResource MenuAddZonePlate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.ZonePlate}" AutomationProperties.AutomationId="AddPart:ZonePlate" />
+ <!-- the part entries, the optics first and the plain shapes after a separator, in one place for both menus that offer
+ them (the menu of kinds and the tree rows' Add part): each entry adds its kind, the class as the parameter. Not
+ shared, so every menu that lists them gets its own entries (added to its items by ProjectTree.MenuEntries) -->
+ <x:Array x:Key="PartMenuEntries" x:Shared="False" Type="{x:Type FrameworkElement}">
+ <MenuItem Header="{DynamicResource MenuAddLens}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:LensPart}" AutomationProperties.AutomationId="AddPart:Lens" />
+ <MenuItem Header="{DynamicResource MenuAddFiber}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:FiberPart}" AutomationProperties.AutomationId="AddPart:Fiber" />
+ <MenuItem Header="{DynamicResource MenuAddBraggReflector}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:BraggReflectorPart}" AutomationProperties.AutomationId="AddPart:BraggReflector" />
+ <MenuItem Header="{DynamicResource MenuAddGrinLens}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:GrinLensPart}" AutomationProperties.AutomationId="AddPart:GrinLens" />
+ <MenuItem Header="{DynamicResource MenuAddZonePlate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:ZonePlatePart}" AutomationProperties.AutomationId="AddPart:ZonePlate" />
<Separator />
- <MenuItem Header="{DynamicResource MenuAddPolygon}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Polygon}" AutomationProperties.AutomationId="AddPart:Polygon" />
- <MenuItem Header="{DynamicResource MenuAddRectangle}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Rectangle}" AutomationProperties.AutomationId="AddPart:Rectangle" />
- <MenuItem Header="{DynamicResource MenuAddEllipse}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Ellipse}" AutomationProperties.AutomationId="AddPart:Ellipse" />
- <MenuItem Header="{DynamicResource MenuAddTriangle}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Triangle}" AutomationProperties.AutomationId="AddPart:Triangle" />
- <MenuItem Header="{DynamicResource MenuAddOutline}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Outline}" AutomationProperties.AutomationId="AddPart:Outline" />
+ <MenuItem Header="{DynamicResource MenuAddPolygon}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:PolygonPart}" AutomationProperties.AutomationId="AddPart:Polygon" />
+ <MenuItem Header="{DynamicResource MenuAddRectangle}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:RectanglePart}" AutomationProperties.AutomationId="AddPart:Rectangle" />
+ <MenuItem Header="{DynamicResource MenuAddEllipse}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:EllipsePart}" AutomationProperties.AutomationId="AddPart:Ellipse" />
+ <MenuItem Header="{DynamicResource MenuAddTriangle}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:TrianglePart}" AutomationProperties.AutomationId="AddPart:Triangle" />
+ <MenuItem Header="{DynamicResource MenuAddOutline}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:OutlinePart}" AutomationProperties.AutomationId="AddPart:Outline" />
<Separator />
<!-- optical logic: one entry per gate (2026-10-21 and 22, the user's requests: XOR, then AND and OR) -->
<MenuItem Header="{DynamicResource MenuAddOpticalLogic}" AutomationProperties.AutomationId="AddPart:OpticalLogic">
- <MenuItem Header="{DynamicResource MenuAddXorGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.XorGate}" AutomationProperties.AutomationId="AddPart:XorGate" />
- <MenuItem Header="{DynamicResource MenuAddAndGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.AndGate}" AutomationProperties.AutomationId="AddPart:AndGate" />
- <MenuItem Header="{DynamicResource MenuAddOrGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.OrGate}" AutomationProperties.AutomationId="AddPart:OrGate" />
+ <MenuItem Header="{DynamicResource MenuAddXorGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:XorGatePart}" AutomationProperties.AutomationId="AddPart:XorGate" />
+ <MenuItem Header="{DynamicResource MenuAddAndGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:AndGatePart}" AutomationProperties.AutomationId="AddPart:AndGate" />
+ <MenuItem Header="{DynamicResource MenuAddOrGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Type model:OrGatePart}" AutomationProperties.AutomationId="AddPart:OrGate" />
</MenuItem>
+ </x:Array>
+ <!-- the menu of part kinds: the "+ Part" button and the Parts folder's plus open it (AddPart without a parameter opens
+ the invoking element's context menu). One instance per button -->
+ <ContextMenu x:Key="PartKindMenu" x:Shared="False" local:ProjectTree.MenuEntries="{StaticResource PartMenuEntries}">
+ <ContextMenu.Resources>
+ <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">
+ <Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
+ </Style>
+ </ContextMenu.Resources>
</ContextMenu>
</UserControl.Resources>
@@ -170,25 +174,7 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
</Style>
</ContextMenu.Resources>
<MenuItem Header="{DynamicResource MenuProjectAddSource}" Command="{x:Static commands:ProjectCommands.AddSource}" />
- <MenuItem Header="{DynamicResource MenuProjectAddPart}">
- <MenuItem Header="{DynamicResource MenuAddLens}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Lens}" />
- <MenuItem Header="{DynamicResource MenuAddFiber}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Fiber}" />
- <MenuItem Header="{DynamicResource MenuAddBraggReflector}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.BraggReflector}" />
- <MenuItem Header="{DynamicResource MenuAddGrinLens}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.GrinLens}" />
- <MenuItem Header="{DynamicResource MenuAddZonePlate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.ZonePlate}" />
- <Separator />
- <MenuItem Header="{DynamicResource MenuAddPolygon}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Polygon}" />
- <MenuItem Header="{DynamicResource MenuAddRectangle}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Rectangle}" />
- <MenuItem Header="{DynamicResource MenuAddEllipse}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Ellipse}" />
- <MenuItem Header="{DynamicResource MenuAddTriangle}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Triangle}" />
- <MenuItem Header="{DynamicResource MenuAddOutline}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.Outline}" />
- <Separator />
- <MenuItem Header="{DynamicResource MenuAddOpticalLogic}">
- <MenuItem Header="{DynamicResource MenuAddXorGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.XorGate}" />
- <MenuItem Header="{DynamicResource MenuAddAndGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.AndGate}" />
- <MenuItem Header="{DynamicResource MenuAddOrGate}" Command="{x:Static commands:ProjectCommands.AddPart}" CommandParameter="{x:Static model:PartKind.OrGate}" />
- </MenuItem>
- </MenuItem>
+ <MenuItem Header="{DynamicResource MenuProjectAddPart}" local:ProjectTree.MenuEntries="{StaticResource PartMenuEntries}" />
<MenuItem Header="{DynamicResource MenuProjectAddProbe}" Command="{x:Static commands:ProjectCommands.AddProbe}" />
<Separator />
<MenuItem Header="{DynamicResource MenuProjectToggleSelected}" Command="{x:Static commands:ProjectCommands.ToggleSelected}" InputGestureText="Ins" AutomationProperties.AutomationId="ContextToggleSelected" />
diff --git a/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs b/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs
index 8cb6ea3..11c6b91 100644
--- a/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs
+++ b/WaveDudeNext.WPF/Panes/ProjectTree.xaml.cs
@@ -62,6 +62,31 @@ public partial class ProjectTree : UserControl
public static readonly DependencyProperty IsInSelectionProperty = DependencyProperty.RegisterAttached(
"IsInSelection", typeof(bool), typeof(ProjectTree), new PropertyMetadata(false));
+ /// <summary>
+ /// Attached to a menu or menu item: the entries (the shared part entries, a fresh set per menu) are added to its Items,
+ /// so they are its logical children as entries written inside it would be. As an ItemsSource they were not, and a
+ /// submenu opened by keyboard the first time put the focus on its last entry instead of its first.
+ /// </summary>
+ public static readonly DependencyProperty MenuEntriesProperty = DependencyProperty.RegisterAttached(
+ "MenuEntries", typeof(IEnumerable), typeof(ProjectTree), new PropertyMetadata(null, OnMenuEntriesChanged));
+
+ /// <summary>Gets the entries attached to <paramref name="menu"/>.</summary>
+ public static IEnumerable? GetMenuEntries(ItemsControl menu) => (IEnumerable?)menu.GetValue(MenuEntriesProperty);
+
+ /// <summary>Attaches <paramref name="entries"/> to <paramref name="menu"/>, which adds them to its items.</summary>
+ public static void SetMenuEntries(ItemsControl menu, IEnumerable? entries) => menu.SetValue(MenuEntriesProperty, entries);
+
+ private static void OnMenuEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ if (d is ItemsControl menu && e.NewValue is IEnumerable entries)
+ {
+ foreach (object entry in entries)
+ {
+ menu.Items.Add(entry);
+ }
+ }
+ }
+
private object? _dragCandidate;
private Point _dragStart;
private InsertionAdorner? _adorner;
diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xaml
index 4163982..090af50 100644
--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml
@@ -717,21 +717,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Hint.LogicGatePart.CladdingIndex">Brechungsindex des Mantels um die Kerne, 1,00 bis 2,55 in Schritten von 0,01.</s:String>
<s:String x:Key="Label.LogicGatePart.PortSpacing">Anschlussabstand</s:String>
<s:String x:Key="Hint.LogicGatePart.PortSpacing">Abstand zwischen den beiden Eingängen und zwischen den beiden Ausgängen in Pixeln. Ein Wert unter dem, was der Entwurf braucht, um die Arme getrennt zu halten, wird darauf angehoben, und das Feld zeigt den verwendeten Abstand.</s:String>
- <s:String x:Key="Enum.PartKind.Lens">Linse oder Spiegel</s:String>
- <s:String x:Key="Enum.PartKind.Polygon">Polygon</s:String>
- <s:String x:Key="Enum.PartKind.Rectangle">Rechteck</s:String>
- <s:String x:Key="Enum.PartKind.Ellipse">Ellipse</s:String>
- <s:String x:Key="Enum.PartKind.Triangle">Dreieck</s:String>
- <s:String x:Key="Enum.PartKind.Outline">Umriss</s:String>
- <s:String x:Key="Enum.PartKind.Fiber">Faser</s:String>
- <s:String x:Key="Enum.PartKind.BraggReflector">Bragg-Reflektor</s:String>
- <s:String x:Key="Enum.PartKind.GrinLens">GRIN-Linse</s:String>
<s:String x:Key="Enum.FiberEnds.Flat">Flach</s:String>
<s:String x:Key="Enum.FiberEnds.Round">Rund</s:String>
- <s:String x:Key="Enum.PartKind.XorGate">XOR-Gatter</s:String>
- <s:String x:Key="Enum.PartKind.AndGate">AND-Gatter</s:String>
- <s:String x:Key="Enum.PartKind.OrGate">OR-Gatter</s:String>
- <s:String x:Key="Enum.PartKind.ZonePlate">Zonenplatte</s:String>
<s:String x:Key="Enum.TriangleType.Equilateral">Gleichseitig</s:String>
<s:String x:Key="Enum.TriangleType.RightIsosceles">Rechtwinklig-gleichschenklig (45°)</s:String>
<s:String x:Key="Enum.TriangleType.ThirtySixtyNinety">30-60-90</s:String>
diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xaml
index 5f16ca3..6f519ab 100644
--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml
@@ -719,21 +719,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Hint.LogicGatePart.CladdingIndex">Refractive index of the cladding around the cores, 1.00 to 2.55 in steps of 0.01.</s:String>
<s:String x:Key="Label.LogicGatePart.PortSpacing">Port spacing</s:String>
<s:String x:Key="Hint.LogicGatePart.PortSpacing">Distance between the two inputs, and between the two outputs, in pixels. A value below what the design needs to keep the arms apart is raised to it, and the box shows the spacing used.</s:String>
- <s:String x:Key="Enum.PartKind.Lens">Lens or mirror</s:String>
- <s:String x:Key="Enum.PartKind.Polygon">Polygon</s:String>
- <s:String x:Key="Enum.PartKind.Rectangle">Rectangle</s:String>
- <s:String x:Key="Enum.PartKind.Ellipse">Ellipse</s:String>
- <s:String x:Key="Enum.PartKind.Triangle">Triangle</s:String>
- <s:String x:Key="Enum.PartKind.Outline">Outline</s:String>
- <s:String x:Key="Enum.PartKind.Fiber">Fibre</s:String>
- <s:String x:Key="Enum.PartKind.BraggReflector">Bragg reflector</s:String>
- <s:String x:Key="Enum.PartKind.GrinLens">GRIN lens</s:String>
<s:String x:Key="Enum.FiberEnds.Flat">Flat</s:String>
<s:String x:Key="Enum.FiberEnds.Round">Round</s:String>
- <s:String x:Key="Enum.PartKind.XorGate">XOR gate</s:String>
- <s:String x:Key="Enum.PartKind.AndGate">AND gate</s:String>
- <s:String x:Key="Enum.PartKind.OrGate">OR gate</s:String>
- <s:String x:Key="Enum.PartKind.ZonePlate">Zone plate</s:String>
<s:String x:Key="Enum.TriangleType.Equilateral">Equilateral</s:String>
<s:String x:Key="Enum.TriangleType.RightIsosceles">Right isosceles (45°)</s:String>
<s:String x:Key="Enum.TriangleType.ThirtySixtyNinety">30-60-90</s:String>
diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xaml
index 98eb441..e1cb16e 100644
--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml
@@ -717,21 +717,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Hint.LogicGatePart.CladdingIndex">Indice de réfraction de la gaine autour des cœurs, de 1,00 à 2,55 par pas de 0,01.</s:String>
<s:String x:Key="Label.LogicGatePart.PortSpacing">Écart des ports</s:String>
<s:String x:Key="Hint.LogicGatePart.PortSpacing">Distance entre les deux entrées, et entre les deux sorties, en pixels. Une valeur inférieure à ce que la conception exige pour garder les bras séparés y est relevée, et la case affiche l'écart utilisé.</s:String>
- <s:String x:Key="Enum.PartKind.Lens">Lentille ou miroir</s:String>
- <s:String x:Key="Enum.PartKind.Polygon">Polygone</s:String>
- <s:String x:Key="Enum.PartKind.Rectangle">Rectangle</s:String>
- <s:String x:Key="Enum.PartKind.Ellipse">Ellipse</s:String>
- <s:String x:Key="Enum.PartKind.Triangle">Triangle</s:String>
- <s:String x:Key="Enum.PartKind.Outline">Contour</s:String>
- <s:String x:Key="Enum.PartKind.Fiber">Fibre</s:String>
- <s:String x:Key="Enum.PartKind.BraggReflector">Réflecteur de Bragg</s:String>
- <s:String x:Key="Enum.PartKind.GrinLens">Lentille GRIN</s:String>
<s:String x:Key="Enum.FiberEnds.Flat">Plates</s:String>
<s:String x:Key="Enum.FiberEnds.Round">Arrondies</s:String>
- <s:String x:Key="Enum.PartKind.XorGate">Porte XOR</s:String>
- <s:String x:Key="Enum.PartKind.AndGate">Porte AND</s:String>
- <s:String x:Key="Enum.PartKind.OrGate">Porte OR</s:String>
- <s:String x:Key="Enum.PartKind.ZonePlate">Lame à zones</s:String>
<s:String x:Key="Enum.TriangleType.Equilateral">Équilatéral</s:String>
<s:String x:Key="Enum.TriangleType.RightIsosceles">Rectangle isocèle (45°)</s:String>
<s:String x:Key="Enum.TriangleType.ThirtySixtyNinety">30-60-90</s:String>
diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xaml
index 460c067..b941cb9 100644
--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml
+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml
@@ -717,21 +717,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<s:String x:Key="Hint.LogicGatePart.CladdingIndex">Brekingsindex van de mantel rond de kernen, 1,00 tot 2,55 in stappen van 0,01.</s:String>
<s:String x:Key="Label.LogicGatePart.PortSpacing">Poortafstand</s:String>
<s:String x:Key="Hint.LogicGatePart.PortSpacing">Afstand tussen de twee ingangen, en tussen de twee uitgangen, in pixels. Een waarde onder wat het ontwerp nodig heeft om de armen gescheiden te houden, wordt daartoe verhoogd, en het vak toont de gebruikte afstand.</s:String>
- <s:String x:Key="Enum.PartKind.Lens">Lens of spiegel</s:String>
- <s:String x:Key="Enum.PartKind.Polygon">Polygoon</s:String>
- <s:String x:Key="Enum.PartKind.Rectangle">Rechthoek</s:String>
- <s:String x:Key="Enum.PartKind.Ellipse">Ellips</s:String>
- <s:String x:Key="Enum.PartKind.Triangle">Driehoek</s:String>
- <s:String x:Key="Enum.PartKind.Outline">Omtrek</s:String>
- <s:String x:Key="Enum.PartKind.Fiber">Vezel</s:String>
- <s:String x:Key="Enum.PartKind.BraggReflector">Bragg-reflector</s:String>
- <s:String x:Key="Enum.PartKind.GrinLens">GRIN-lens</s:String>
<s:String x:Key="Enum.FiberEnds.Flat">Vlak</s:String>
<s:String x:Key="Enum.FiberEnds.Round">Rond</s:String>
- <s:String x:Key="Enum.PartKind.XorGate">XOR-poort</s:String>
- <s:String x:Key="Enum.PartKind.AndGate">AND-poort</s:String>
- <s:String x:Key="Enum.PartKind.OrGate">OR-poort</s:String>
- <s:String x:Key="Enum.PartKind.ZonePlate">Zoneplaat</s:String>
<s:String x:Key="Enum.TriangleType.Equilateral">Gelijkzijdig</s:String>
<s:String x:Key="Enum.TriangleType.RightIsosceles">Rechthoekig-gelijkbenig (45°)</s:String>
<s:String x:Key="Enum.TriangleType.ThirtySixtyNinety">30-60-90</s:String>
diff --git a/WaveDudeNext.WPF/Themes/Controls.xaml b/WaveDudeNext.WPF/Themes/Controls.xaml
index 76b172c..eadc214 100644
--- a/WaveDudeNext.WPF/Themes/Controls.xaml
+++ b/WaveDudeNext.WPF/Themes/Controls.xaml
@@ -209,6 +209,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{DynamicResource MenuForeground}" />
<Setter Property="Padding" Value="7,3" />
+ <!-- set here so the system theme's bindings to the parent ItemsControl never apply: the templates below do not use
+ them, and a menu item made before its menu (the shared part entries in ProjectTree.xaml) logged a binding error -->
+ <Setter Property="HorizontalContentAlignment" Value="Left" />
+ <Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template" Value="{StaticResource MenuSubmenuItemTemplate}" />
<Style.Triggers>
<Trigger Property="Role" Value="TopLevelHeader">
diff --git a/WaveDudeNext/Model/OpticalPart.cs b/WaveDudeNext/Model/OpticalPart.cs
index ac07fba..90c36a7 100644
--- a/WaveDudeNext/Model/OpticalPart.cs
+++ b/WaveDudeNext/Model/OpticalPart.cs
@@ -24,37 +24,6 @@ using WaveDudeNext.Parts;
namespace WaveDudeNext.Model;
-/// <summary>The kinds of optical part; one subclass of <see cref="OpticalPart"/> and one project file element per kind.</summary>
-public enum PartKind
-{
- /// <summary>A lens or a curved or flat mirror (<see cref="LensPart"/>).</summary>
- Lens,
- /// <summary>A regular polygon (<see cref="PolygonPart"/>).</summary>
- Polygon,
- /// <summary>A rectangle (<see cref="RectanglePart"/>).</summary>
- Rectangle,
- /// <summary>An ellipse or circle (<see cref="EllipsePart"/>).</summary>
- Ellipse,
- /// <summary>A triangle shaped by its base angles (<see cref="TrianglePart"/>).</summary>
- Triangle,
- /// <summary>A free outline from a point list (<see cref="OutlinePart"/>).</summary>
- Outline,
- /// <summary>A fibre with a core and a cladding along a path (<see cref="FiberPart"/>).</summary>
- Fiber,
- /// <summary>A stack of alternating layers (<see cref="BraggReflectorPart"/>).</summary>
- BraggReflector,
- /// <summary>A gradient-index lens (<see cref="GrinLensPart"/>).</summary>
- GrinLens,
- /// <summary>An optical XOR gate: two waveguides and a directional coupler designed for one wavelength (<see cref="XorGatePart"/>).</summary>
- XorGate,
- /// <summary>An optical AND gate, the same coupler with the in-phase sum on the upper output (<see cref="AndGatePart"/>).</summary>
- AndGate,
- /// <summary>An optical OR gate, the same coupler with the waves meeting at 120° on the upper output (<see cref="OrGatePart"/>).</summary>
- OrGate,
- /// <summary>A Fresnel zone plate, a diffractive lens of absorbing zones (<see cref="ZonePlatePart"/>).</summary>
- ZonePlate,
-}
-
/// <summary>
/// An optical part placed on the canvas: a lens or mirror, a shape (polygon, rectangle, triangle, outline), a fibre, a
/// Bragg reflector or a GRIN lens (Jeroen
@@ -142,10 +111,18 @@ public abstract class OpticalPart : ObservableObject, IMovable
set => SetProperty(ref _angle, value);
}
- /// <summary>The kind of part, for the tree row and the overlay; fixed per subclass.</summary>
+ /// <summary>The English stem of a new part's name ("Lens", "Bragg reflector", …), numbered by <see cref="Project.AddPart(Type)"/>; fixed per subclass.</summary>
[XmlIgnore]
[Browsable(false)]
- public abstract PartKind Kind { get; }
+ public abstract string NameStem { get; }
+
+ /// <summary>
+ /// Gives a part made by <see cref="Project.AddPart(Type)"/> what a new part starts with and a loaded one must not get
+ /// (a fibre's default path: <see cref="XmlSerializer"/> appends a file's items to the list it finds). Does nothing by default.
+ /// </summary>
+ public virtual void PrepareNew()
+ {
+ }
/// <summary>Half-extent of the part along its axis in canvas pixels, so the rotation handle can sit beyond it. UI thread.</summary>
[XmlIgnore]
@@ -297,7 +274,7 @@ public sealed class LensPart : OpticalPart
private int _thickness = DefaultThickness;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Lens;
+ public override string NameStem => "Lens";
/// <summary>Whether the part is a mirror (red 0, a wall no wave gets through) instead of a lens; the index, the coating and the absorption are ignored then.</summary>
[XmlAttribute]
@@ -692,7 +669,7 @@ public sealed class PolygonPart : ShapePart
private int _side = DefaultSide;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Polygon;
+ public override string NameStem => "Polygon";
/// <summary>Number of sides, 3 to 64.</summary>
[XmlAttribute]
@@ -762,7 +739,7 @@ public sealed class RectanglePart : ShapePart
private bool _linked;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Rectangle;
+ public override string NameStem => "Rectangle";
/// <summary>Extent along the axis in pixels.</summary>
[XmlAttribute]
@@ -859,7 +836,7 @@ public sealed class EllipsePart : ShapePart
private bool _linked;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Ellipse;
+ public override string NameStem => "Ellipse";
/// <summary>Diameter along the axis in pixels.</summary>
[XmlAttribute]
@@ -988,7 +965,7 @@ public sealed class TrianglePart : ShapePart
private double _angleB = 60.0;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Triangle;
+ public override string NameStem => "Triangle";
/// <summary>Length of the base in pixels.</summary>
[XmlAttribute]
@@ -1123,7 +1100,7 @@ public sealed class OutlinePart : ShapePart
private ObservableCollection<PartPoint> _points = [];
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Outline;
+ public override string NameStem => "Outline";
/// <summary>The outline's vertices relative to the centre, before rotation; fewer than three points paint nothing.</summary>
[XmlElement("Point")]
@@ -1369,7 +1346,10 @@ public sealed class FiberPart : OpticalPart
}
/// <inheritdoc/>
- public override PartKind Kind => PartKind.Fiber;
+ public override string NameStem => "Fiber";
+
+ /// <summary>A new fibre gets the <see cref="DefaultPath"/>.</summary>
+ public override void PrepareNew() => Nodes = DefaultPath();
/// <summary>Refractive index of the core, 1.00 to 2.55.</summary>
[XmlAttribute]
@@ -1484,7 +1464,7 @@ public sealed class FiberPart : OpticalPart
/// <summary>
/// The default straight path, from (-100, 0) to (100, 0), the handles a third of the way along it so they can be
- /// taken hold of. Given to a new fibre by <see cref="Project.AddPart"/>, not by the constructor:
+ /// taken hold of. Given to a new fibre by <see cref="PrepareNew"/>, not by the constructor:
/// <see cref="XmlSerializer"/> appends a file's nodes to the list it finds, so the constructor's list must be empty.
/// </summary>
public static ObservableCollection<FiberNode> DefaultPath()
@@ -1777,7 +1757,7 @@ public sealed class BraggReflectorPart : OpticalPart
private int _width = DefaultWidth;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.BraggReflector;
+ public override string NameStem => "Bragg reflector";
/// <summary>Number of layer pairs, 1 to 200.</summary>
[XmlAttribute]
@@ -1911,7 +1891,7 @@ public sealed class GrinLensPart : OpticalPart
private int _coating;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.GrinLens;
+ public override string NameStem => "GRIN lens";
/// <summary>Extent along the axis in pixels.</summary>
[XmlAttribute]
@@ -2346,7 +2326,7 @@ public abstract class LogicGatePart : OpticalPart, IFrequencyDesigned
public sealed class XorGatePart : LogicGatePart
{
/// <inheritdoc/>
- public override PartKind Kind => PartKind.XorGate;
+ public override string NameStem => "XOR gate";
/// <inheritdoc/>
public override double PhaseShift => 90.0;
@@ -2369,7 +2349,7 @@ public sealed class XorGatePart : LogicGatePart
public sealed class AndGatePart : LogicGatePart
{
/// <inheritdoc/>
- public override PartKind Kind => PartKind.AndGate;
+ public override string NameStem => "AND gate";
/// <inheritdoc/>
public override double PhaseShift => -90.0;
@@ -2391,7 +2371,7 @@ public sealed class AndGatePart : LogicGatePart
public sealed class OrGatePart : LogicGatePart
{
/// <inheritdoc/>
- public override PartKind Kind => PartKind.OrGate;
+ public override string NameStem => "OR gate";
/// <inheritdoc/>
public override double PhaseShift => 30.0;
@@ -2451,7 +2431,7 @@ public sealed class ZonePlatePart : OpticalPart, IFrequencyDesigned
public const int DefaultMountWidth = 200;
/// <inheritdoc/>
- public override PartKind Kind => PartKind.ZonePlate;
+ public override string NameStem => "Zone plate";
/// <summary>
/// Whether an absorbing mount surrounds the plate (the user's request, 2026-10-22): a band of <see cref="MountWidth"/>
diff --git a/WaveDudeNext/Model/Project.cs b/WaveDudeNext/Model/Project.cs
index 1429571..d334f86 100644
--- a/WaveDudeNext/Model/Project.cs
+++ b/WaveDudeNext/Model/Project.cs
@@ -339,54 +339,28 @@ public sealed class Project : ObservableObject
}
/// <summary>
- /// Appends a new part of <paramref name="kind"/>, named "Lens n", "Polygon n", "Rectangle n", "Ellipse n", "Triangle n", "Outline n",
- /// "Fiber n", "Bragg reflector n", "GRIN lens n", "XOR gate n", "AND gate n", "OR gate n" or "Zone plate n" with the first free n, centred on the canvas (the scene's size; an image scene's own size is not
- /// known here), and returns it.
+ /// Appends a new part of the concrete <see cref="OpticalPart"/> subclass <paramref name="type"/> (the "+ Part" menu's
+ /// parameter), prepared as new (<see cref="OpticalPart.PrepareNew"/>), named by its <see cref="OpticalPart.NameStem"/>
+ /// with the first free n ("Lens 1", "Bragg reflector 2"), centred on the canvas (the scene's size; an image scene's own
+ /// size is not known here), and returns it.
/// </summary>
- public OpticalPart AddPart(PartKind kind)
+ public OpticalPart AddPart(Type type)
{
- OpticalPart part = kind switch
+ if (!type.IsSubclassOf(typeof(OpticalPart)) || type.IsAbstract)
{
- PartKind.Lens => new LensPart(),
- PartKind.Polygon => new PolygonPart(),
- PartKind.Rectangle => new RectanglePart(),
- PartKind.Ellipse => new EllipsePart(),
- PartKind.Triangle => new TrianglePart(),
- PartKind.Outline => new OutlinePart(),
- PartKind.Fiber => new FiberPart { Nodes = FiberPart.DefaultPath() },
- PartKind.BraggReflector => new BraggReflectorPart(),
- PartKind.GrinLens => new GrinLensPart(),
- PartKind.XorGate => new XorGatePart(),
- PartKind.AndGate => new AndGatePart(),
- PartKind.OrGate => new OrGatePart(),
- PartKind.ZonePlate => new ZonePlatePart(),
- _ => throw new ArgumentOutOfRangeException(nameof(kind)),
- };
- part.Name = NumberedName(PartStem(kind), Parts.Select(p => p.Name));
+ throw new ArgumentException($"{type.Name} is not a concrete optical part", nameof(type));
+ }
+ var part = (OpticalPart)Activator.CreateInstance(type)!;
+ part.PrepareNew();
+ part.Name = NumberedName(part.NameStem, Parts.Select(p => p.Name));
part.X = Scene.Width / 2;
part.Y = Scene.Height / 2;
Parts.Add(part);
return part;
}
- /// <summary>The English name stem of new parts of <paramref name="kind"/> ("Lens", "Bragg reflector", …).</summary>
- public static string PartStem(PartKind kind) => kind switch
- {
- PartKind.Lens => "Lens",
- PartKind.Polygon => "Polygon",
- PartKind.Rectangle => "Rectangle",
- PartKind.Ellipse => "Ellipse",
- PartKind.Triangle => "Triangle",
- PartKind.Outline => "Outline",
- PartKind.Fiber => "Fiber",
- PartKind.BraggReflector => "Bragg reflector",
- PartKind.GrinLens => "GRIN lens",
- PartKind.XorGate => "XOR gate",
- PartKind.AndGate => "AND gate",
- PartKind.OrGate => "OR gate",
- PartKind.ZonePlate => "Zone plate",
- _ => "Part",
- };
+ /// <summary>Appends a new part of type <typeparamref name="T"/> as <see cref="AddPart(Type)"/> does, and returns it.</summary>
+ public T AddPart<T>() where T : OpticalPart, new() => (T)AddPart(typeof(T));
/// <summary>Appends a new probe named "Probe n" with the first free n, and returns it.</summary>
public Probe AddProbe()
diff --git a/WaveDudeNext/Parts/PartPainter.cs b/WaveDudeNext/Parts/PartPainter.cs
index 0c6d401..bebedc9 100644
--- a/WaveDudeNext/Parts/PartPainter.cs
+++ b/WaveDudeNext/Parts/PartPainter.cs
@@ -101,16 +101,16 @@ public static class PartPainter
PartShape? shape = PartShape.For(part);
if (shape == null)
{
- Logger.Debug("Part '{Name}' ({Kind}) has no shape to paint (too few points)", part.Name, part.Kind);
+ Logger.Debug("Part '{Name}' ({Type}) has no shape to paint (too few points)", part.Name, part.GetType().Name);
return;
}
(int x0, int y0, int x1, int y1) = shape.Bounds(width, height);
if (x0 > x1 || y0 > y1)
{
- Logger.Debug("Part '{Name}' ({Kind}) lies outside the canvas", part.Name, part.Kind);
+ Logger.Debug("Part '{Name}' ({Type}) lies outside the canvas", part.Name, part.GetType().Name);
return;
}
- Logger.Debug("Painting part '{Name}' ({Kind}) at ({X}, {Y}), {Angle}°, rows {Y0}..{Y1}", part.Name, part.Kind, part.X, part.Y, part.Angle, y0, y1);
+ Logger.Debug("Painting part '{Name}' ({Type}) at ({X}, {Y}), {Angle}°, rows {Y0}..{Y1}", part.Name, part.GetType().Name, part.X, part.Y, part.Angle, y0, y1);
if (shape.Absorption > 0)
{
PaintAbsorption(bgra, stride, shape, x0, y0, x1, y1);
diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.cs
index ba6dbac..8c88e42 100644
--- a/_tools/library_check/Program.cs
+++ b/_tools/library_check/Program.cs
@@ -194,17 +194,17 @@ internal static class Program
var project = new Project();
project.Scene.Width = 1920;
project.Scene.Height = 1080;
- var outline = (OutlinePart)project.AddPart(PartKind.Outline);
+ var outline = project.AddPart<OutlinePart>();
foreach ((int px, int py) in new[] { (-200, -150), (200, -120), (150, 180), (-180, 120) })
{
outline.Points.Add(new PartPoint { X = px, Y = py });
}
- var lens = (LensPart)project.AddPart(PartKind.Lens);
+ var lens = project.AddPart<LensPart>();
lens.Diameter = 400;
- var polygon = (PolygonPart)project.AddPart(PartKind.Polygon);
+ var polygon = project.AddPart<PolygonPart>();
polygon.Side = 150;
// a fibre in an S-bend across the whole canvas: its bounding box is the canvas (2026-10-22)
- var fiber = (FiberPart)project.AddPart(PartKind.Fiber);
+ var fiber = project.AddPart<FiberPart>();
fiber.Nodes[0].X = -900;
fiber.Nodes[0].SetHandle(true, 400, -500);
fiber.Nodes[1].X = 900;
@@ -218,7 +218,7 @@ internal static class Program
{
PartPainter.Paint(null, 1920, 1080, 1.0, single);
}
- Console.WriteLine($" {part.Kind}: {timer.Elapsed.TotalMilliseconds / 10:0.0} ms per paint");
+ Console.WriteLine($" {part.NameStem}: {timer.Elapsed.TotalMilliseconds / 10:0.0} ms per paint");
}
var blank = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
@@ -843,7 +843,7 @@ internal static class Program
Source source = project.AddSource();
source.X = 10;
source.Y = 10;
- OpticalPart part = project.AddPart(PartKind.Rectangle);
+ OpticalPart part = project.AddPart<RectanglePart>();
part.X = 50;
part.Y = 40;
Probe probe = project.AddProbe();
@@ -2083,7 +2083,7 @@ internal static class Program
project.Scene.Width = W;
project.Scene.Height = H;
Check(ReferenceEquals(PartPainter.Paint(image, W, H, 1.0, project.Parts), image) && PartPainter.Paint(null, W, H, 1.0, project.Parts) == null, "no enabled part: the painter returns the image itself (null for a canvas)");
- var lens = (LensPart)project.AddPart(PartKind.Lens);
+ var lens = project.AddPart<LensPart>();
lens.Enabled = false;
Check(ReferenceEquals(PartPainter.Paint(image, W, H, 1.0, project.Parts), image), "a disabled part leaves the image untouched");
lens.Enabled = true;
@@ -2093,7 +2093,7 @@ internal static class Program
lens.R1 = 300;
lens.R2 = -300;
lens.Thickness = 40;
- Check(lens.Name == "Lens 1" && lens.RefractiveIndex == 1.5 && lens.Kind == PartKind.Lens, "a new lens: 'Lens 1', index 1.5");
+ Check(lens.Name == "Lens 1" && lens.RefractiveIndex == 1.5, "a new lens: 'Lens 1', index 1.5");
ScenePixels painted = PartPainter.Paint(image, W, H, 1.0, project.Parts)!;
Check(!ReferenceEquals(painted, image) && painted.Width == W && painted.Height == H && image.Bgra[60 * stride + 100 * 4 + 2] == 100, "an enabled part paints a copy; the image is not modified");
Check(painted.Bgra[60 * painted.StrideBytes + 100 * 4 + 1] == 160 && painted.Bgra[60 * painted.StrideBytes + 100 * 4] == 33 && painted.Bgra[5 * painted.StrideBytes + 5 * 4] == 77, "green and blue are untouched under the lens");
@@ -2167,7 +2167,7 @@ internal static class Program
project.Parts.Clear();
// the shapes: a regular hexagon's area, a rectangle, triangles, an outline; then a GRIN lens, a Bragg stack, a fibre
- var hexagon = (PolygonPart)project.AddPart(PartKind.Polygon);
+ var hexagon = project.AddPart<PolygonPart>();
hexagon.X = 100;
hexagon.Y = 60;
hexagon.Sides = 6;
@@ -2179,7 +2179,7 @@ internal static class Program
Check(RedAt(painted, 100 + 24, 60) == 150 && RedAt(painted, 100 + 26, 60) == 100 && RedAt(painted, 100, 60 + 14) == 150 && RedAt(painted, 100, 60 + 30) == 100, "the hexagon has flat faces at ±x' (26 px out) and vertices at ±y' (30 px out)");
Check(painted.Bgra[(60 * W + 100) * 4 + 3] == 255 && painted.Bgra[(60 * W + 100) * 4 + 1] == 0 && painted.Bgra[(0 * W + 0) * 4 + 2] == 100, "a blank canvas: opaque, no green, background red 100");
project.Parts.Clear();
- var rectangle = (RectanglePart)project.AddPart(PartKind.Rectangle);
+ var rectangle = project.AddPart<RectanglePart>();
rectangle.X = 100;
rectangle.Y = 60;
rectangle.Length = 60;
@@ -2189,7 +2189,7 @@ internal static class Program
Check(Math.Abs(area - 1200.0) < 2.0 && RedAt(painted, 100 - 30, 60) == 150 && RedAt(painted, 100 - 31, 60) == 100 && RedAt(painted, 100 + 29, 60) == 150 && RedAt(painted, 100, 60 + 9) == 150 && RedAt(painted, 100, 60 + 10) == 100,
$"a rectangle of length 60 and width 20 lies square to the axis, x = 70..129, y = 50..69 ({area:F1} px)");
project.Parts.Clear();
- var ellipse = (EllipsePart)project.AddPart(PartKind.Ellipse);
+ var ellipse = project.AddPart<EllipsePart>();
ellipse.X = 100;
ellipse.Y = 60;
ellipse.Length = 60;
@@ -2219,7 +2219,7 @@ internal static class Program
ellipse.Linked = true;
Check(ellipse.Width == 60 && ellipse.Vertices().All(v => Math.Abs(Math.Sqrt(v.X * v.X + v.Y * v.Y) - 30) < 1e-9), "a linked ellipse is a circle");
project.Parts.Clear();
- var triangle = (TrianglePart)project.AddPart(PartKind.Triangle);
+ var triangle = project.AddPart<TrianglePart>();
triangle.X = 100;
triangle.Y = 60;
triangle.Base = 60;
@@ -2247,7 +2247,7 @@ internal static class Program
Check(Math.Abs(area - 1558.8) < 0.01 * 1558.8 && RedAt(painted, 100 - 25, 60) == 150 && RedAt(painted, 100 - 27, 60) == 100 && RedAt(painted, 100 + 20, 60) == 150 && RedAt(painted, 100 + 27, 60) == 100,
$"the painted equilateral triangle covers {area:F1} px of 1558.8, the base at x' = -26, the apex at +26");
project.Parts.Clear();
- var outline = (OutlinePart)project.AddPart(PartKind.Outline);
+ var outline = project.AddPart<OutlinePart>();
outline.X = 100;
outline.Y = 60;
Check(PartShape.For(outline) == null && ReferenceEquals(PartPainter.Paint(image, W, H, 1.0, project.Parts), image) == false && RedAt(PartPainter.Paint(null, W, H, 1.0, project.Parts)!, 100, 60) == 100, "an outline without points paints nothing");
@@ -2259,7 +2259,7 @@ internal static class Program
area = PaintedArea(painted, 1.5);
Check(Math.Abs(area - 200.0) < 2.0 && RedAt(painted, 100, 60) == 150 && RedAt(painted, 100, 60 + 6) == 100, $"four points make a 20 × 10 outline ({area:F1} px)");
project.Parts.Clear();
- var grin = (GrinLensPart)project.AddPart(PartKind.GrinLens);
+ var grin = project.AddPart<GrinLensPart>();
grin.X = 100;
grin.Y = 60;
painted = PartPainter.Paint(null, W, H, 1.0, project.Parts)!;
@@ -2267,7 +2267,7 @@ internal static class Program
Check(RedAt(painted, 100, 60) == 180 && RedAt(painted, 100, 60 + 25) == 172 && RedAt(painted, 100, 60 + 48) == 152 && RedAt(painted, 100, 60 + 50) == 100 && RedAt(painted, 100 + 49, 60) == 180 && RedAt(painted, 100 + 50, 60) == 100,
"a GRIN lens 100 × 100: index 1.8 on the axis falling parabolically to 1.5 at the edge, 1 outside");
project.Parts.Clear();
- var bragg = (BraggReflectorPart)project.AddPart(PartKind.BraggReflector);
+ var bragg = project.AddPart<BraggReflectorPart>();
bragg.X = 100;
bragg.Y = 60;
bragg.Pairs = 3;
@@ -2279,7 +2279,7 @@ internal static class Program
Check(layers == "." + string.Concat(Enumerable.Repeat("1111111111222222", 3)) + "." && RedAt(painted, 100, 60 + 9) == 150 && RedAt(painted, 100, 60 + 10) == 100,
"a Bragg stack of 3 pairs 10 + 6 px, indices 1.5 / 2.0, 20 wide, centred: " + layers);
project.Parts.Clear();
- var fiber = (FiberPart)project.AddPart(PartKind.Fiber);
+ var fiber = project.AddPart<FiberPart>();
fiber.X = 80;
fiber.Y = 60;
painted = PartPainter.Paint(null, W, H, 1.0, project.Parts)!;
@@ -2336,7 +2336,7 @@ internal static class Program
twin.Nodes[1].OutX = 0;
Check(twin.Nodes[1] is { OutX: 0, OutY: 37, InX: 0, InY: -37 } && bare is { InX: -37, OutX: 37, OutY: 0 }, "a clone keeps its own nodes smooth, the original's untouched");
var keeper = new Project();
- var kept = (FiberPart)keeper.AddPart(PartKind.Fiber);
+ var kept = keeper.AddPart<FiberPart>();
kept.Nodes.Add(new FiberNode { X = 150, Y = 30, InX = -60, OutX = 60, OutY = 1 });
string keptXml;
using (var stream = new MemoryStream())
@@ -2360,7 +2360,7 @@ internal static class Program
const int cw = 64, ch = 48;
project.Scene.Width = cw;
project.Scene.Height = ch;
- var wall = (OutlinePart)project.AddPart(PartKind.Outline);
+ var wall = project.AddPart<OutlinePart>();
wall.X = 32;
wall.Y = 24;
wall.Mirror = true;
@@ -2368,7 +2368,7 @@ internal static class Program
{
wall.Points.Add(new PartPoint { X = px, Y = py });
}
- var hollow = (OutlinePart)project.AddPart(PartKind.Outline);
+ var hollow = project.AddPart<OutlinePart>();
hollow.X = 32;
hollow.Y = 24;
hollow.RefractiveIndex = 1.0;
@@ -2420,25 +2420,25 @@ internal static class Program
project.Scene.Width = W;
project.Scene.Height = H;
project.Parts.Clear();
- project.AddPart(PartKind.Lens);
- var polygon = (OutlinePart)project.AddPart(PartKind.Outline);
+ project.AddPart<LensPart>();
+ var polygon = project.AddPart<OutlinePart>();
polygon.Points.Add(new PartPoint { X = 3, Y = -4 });
polygon.Mirror = true;
- project.AddPart(PartKind.Polygon);
- ((RectanglePart)project.AddPart(PartKind.Rectangle)).Width = 7;
- var roundOne = (EllipsePart)project.AddPart(PartKind.Ellipse);
+ project.AddPart<PolygonPart>();
+ project.AddPart<RectanglePart>().Width = 7;
+ var roundOne = project.AddPart<EllipsePart>();
roundOne.Linked = true;
roundOne.Width = 9;
- ((TrianglePart)project.AddPart(PartKind.Triangle)).Type = TriangleType.RightIsosceles;
- project.AddPart(PartKind.Fiber);
- var reflector = (BraggReflectorPart)project.AddPart(PartKind.BraggReflector);
+ project.AddPart<TrianglePart>().Type = TriangleType.RightIsosceles;
+ project.AddPart<FiberPart>();
+ var reflector = project.AddPart<BraggReflectorPart>();
reflector.Angle = 45;
reflector.Index2 = 2.2;
- project.AddPart(PartKind.GrinLens);
+ project.AddPart<GrinLensPart>();
OpticalPart copy = project.Duplicate(reflector);
Check(copy is BraggReflectorPart { Name: "Bragg reflector 1 copy", Angle: 45, Index2: 2.2 } && project.Parts.IndexOf(copy) == 8 && project.Parts.Count == 10, "Duplicate: a deep copy right after the original, named '… copy'");
Check(project.Remove(copy) && project.Move(reflector, 0) && project.Parts[0] == reflector && project.Parts.Count == 9, "Remove and Move work on the parts list");
- ((XorGatePart)project.AddPart(PartKind.XorGate)).DesignFrequency = 80;
+ project.AddPart<XorGatePart>().DesignFrequency = 80;
string xml;
using (var stream = new MemoryStream())
{
@@ -2458,8 +2458,14 @@ internal static class Program
{
back = Project.Load(stream);
}
- Check(back.Parts.Count == 10 && back.Parts.Select(p => p.Kind).SequenceEqual([PartKind.BraggReflector, PartKind.Lens, PartKind.Outline, PartKind.Polygon, PartKind.Rectangle, PartKind.Ellipse, PartKind.Triangle, PartKind.Fiber, PartKind.GrinLens, PartKind.XorGate])
+ Check(back.Parts.Count == 10 && back.Parts.Select(p => p.GetType()).SequenceEqual([typeof(BraggReflectorPart), typeof(LensPart), typeof(OutlinePart), typeof(PolygonPart), typeof(RectanglePart), typeof(EllipsePart), typeof(TrianglePart), typeof(FiberPart), typeof(GrinLensPart), typeof(XorGatePart)])
&& back.Parts[9] is XorGatePart { DesignFrequency: 80 }, "the ten kinds load back in order");
+ // the class is the kind: every part class has its file element and is added by its type, so none is half wired
+ Type[] partTypes = [.. typeof(OpticalPart).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(OpticalPart)) && !type.IsAbstract)];
+ HashSet<Type?> elements = [.. typeof(Project).GetProperty(nameof(Project.Parts))!.GetCustomAttributes<XmlElementAttribute>().Select(element => element.Type)];
+ var adder = new Project();
+ Check(partTypes.Length > 0 && partTypes.All(type => elements.Contains(type) && adder.AddPart(type) is { } added && added.GetType() == type && added.Name == added.NameStem + " 1"),
+ $"each of the {partTypes.Length} part classes has its file element and is added by its type as '<stem> 1'");
Check(xml.Contains("<Node X=\"-100\" Y=\"0\" OutX=\"67\" />") && xml.Contains("<Node X=\"100\" Y=\"0\" InX=\"-67\" />"), "a fibre's nodes are sparse Node children: handles only where set, Smooth only when off");
Check(back.Parts[7] is FiberPart { Nodes.Count: 2, Ends: FiberEnds.Flat } loaded && loaded.Nodes[0] is { X: -100, OutX: 67, Smooth: true } && loaded.Nodes[1] is { X: 100, InX: -67 }, "a loaded fibre has its two nodes with their handles, not the default path on top of them");
Check(back.Parts[2] is OutlinePart { Mirror: true, Points.Count: 1 } && back.Parts[0] is BraggReflectorPart { Angle: 45, Index2: 2.2, Pairs: 10 } && back.Parts[4] is RectanglePart { Width: 7, Length: 60 } && back.Parts[5] is EllipsePart { Width: 9, Length: 9, Linked: true } && back.Parts[6] is TrianglePart { Type: TriangleType.RightIsosceles, AngleB: 45 },
@@ -2648,7 +2654,7 @@ internal static class Program
foreach (LogicGatePart other in new LogicGatePart[] { new AndGatePart { X = gate.X, Y = gate.Y }, new OrGatePart { X = gate.X, Y = gate.Y } })
{
Check(other.Design!.Length == design.Length && other.Design.PortSpacing == design.PortSpacing && other.Ports()!.SequenceEqual(ports),
- $"the {other.Kind} has the XOR gate's dimensions and ports ({2 * other.Design.PortSpacing} × {other.Design.Length} px; phase section {other.Design.PhaseLength} of {other.Design.PhaseRegionLength} px on arm {(other.Design.PhaseOnArmA ? "A" : "B")})");
+ $"the {other.NameStem} has the XOR gate's dimensions and ports ({2 * other.Design.PortSpacing} × {other.Design.Length} px; phase section {other.Design.PhaseLength} of {other.Design.PhaseRegionLength} px on arm {(other.Design.PhaseOnArmA ? "A" : "B")})");
ScenePixels otherPixels = PartPainter.Paint(null, width, height, 1.0, [other])!;
SceneData otherScene = SceneData.FromBgra(otherPixels.Bgra, width, height, otherPixels.StrideBytes, false, 0, true);
(double upperA, double lowerA, _) = Outputs([Make(ports[0].X, ports[0].Y, 0, 1.0) with { Level = level }], otherScene);
@@ -2770,7 +2776,7 @@ internal static class Program
private static void CheckGatePortFollower()
{
var project = new Project();
- var gate = (XorGatePart)project.AddPart(PartKind.XorGate);
+ var gate = project.AddPart<XorGatePart>();
(int X, int Y)[] ports = gate.Ports()!;
var a = new Source { Name = "A", X = ports[0].X, Y = ports[0].Y };
var b = new Source { Name = "B", X = ports[1].X + 1, Y = ports[1].Y - 1 };
@@ -2793,7 +2799,7 @@ internal static class Program
(int X, int Y) bBefore = (b.X, b.Y);
Movable.MoveAll([gate, a], 7, -3);
Check(OnInputs() && (b.X, b.Y) == (bBefore.X + 7, bBefore.Y - 3), "a group move of the gate with A moves A once, and B follows the gate");
- var second = (XorGatePart)project.AddPart(PartKind.XorGate);
+ var second = project.AddPart<XorGatePart>();
second.Y = 200;
var c = new Source { Name = "C", X = second.Ports()![0].X, Y = second.Ports()![0].Y };
project.Sources.Add(c);
@@ -2812,7 +2818,7 @@ internal static class Program
project.Scene.Width = W;
project.Scene.Height = H;
// a 100 × 100 square of index 1 centred on the corner of pixel (100, 60): x = 50..149, y = 10..109
- var square = (RectanglePart)project.AddPart(PartKind.Rectangle);
+ var square = project.AddPart<RectanglePart>();
square.X = 100;
square.Y = 60;
square.Length = 100;
@@ -2847,7 +2853,7 @@ internal static class Program
square.Mirror = false;
// the lens carries the same two settings
project.Remove(square);
- var lens = (LensPart)project.AddPart(PartKind.Lens);
+ var lens = project.AddPart<LensPart>();
lens.X = 100;
lens.Y = 60;
lens.Diameter = 100;