using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Input; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Rendering.SceneGraph; using Avalonia.Skia; using OpenNest.Avalonia.Rendering; using OpenNest.CNC; using OpenNest.CommonLines; using OpenNest.CutOffs; using OpenNest.Desktop.Interaction; using OpenNest.Desktop.Rendering; using OpenNest.Engine.Fill; using OpenNest.Geometry; using OpenNest.Support; using SkiaSharp; using Control = Avalonia.Controls.Control; using Vector = OpenNest.Geometry.Vector; namespace OpenNest.Avalonia.Controls { /// /// Draws one plate with Skia as the WinForms plate view does, in the colours of /// : the sheet (or irregular outline), edge spacing, filled parts with their /// numbers, cut-offs, clamps, common lines and the View toggles in . Pans /// with a middle drag, zooms at the cursor with the wheel, fits on a middle double click, and /// highlights the part under the cursor. Left and right clicks go to the active plate tool /// (, Select by default); Escape steps out of it. /// public sealed class PlateCanvas : Control, IPlateToolHost { // Paths are built once per part pose and only read afterwards, so the render thread may draw // them while the UI thread builds others. private readonly Dictionary paths = new(); private readonly Dictionary labelPoints = new(); private readonly ConditionalWeakTable offsets = new(); private readonly SupportAnalysisCache supports = new(); private readonly Dictionary commonLineChecks = new(); private readonly ViewTransform view = new(); private readonly PlateSelection selection = new(); private readonly PlateHitTester hitTester; private readonly PlateToolManager tools; private Plate plate; private Point? panStart; // Where the middle button went down: a press released within 5 px turns the selection. private Point? middleDown; private bool fitPending = true; private sealed record OffsetEntry(CNC.Program Program, double Rotation, double Spacing, double Tolerance, SKPath Path); public Plate Plate { get => plate; set { var changed = !ReferenceEquals(plate, value); plate = value; HoveredPart = null; if (changed) { selection.Plate = value; tools.OnPlateChanged(); } fitPending = true; TrimCache(); InvalidateVisual(); } } /// /// Shows , a copy of the shown plate an Undo or Redo read back, /// keeping the zoom and pan, and selects its parts at /// (indices off the plate are skipped). /// public void ReplacePlate(Plate value, IEnumerable selectedIndices) { var fit = fitPending; Plate = value; fitPending = fit; selection.SelectIndices(selectedIndices); } /// The colours drawn with: the application's active scheme unless set. public ColorScheme Scheme { get; set; } = ColorScheme.Default; /// The View menu toggles this view draws with. public PlateViewOptions Options { get; set; } = new(); public Part HoveredPart { get; private set; } /// The parts and cut-offs selected on the shown plate. public PlateSelection Selection => selection; /// The active plate tool and its status text. public PlateToolManager Tools => tools; public PlateHitTester HitTester => hitTester; /// Delete, nudge, push and rotate the selection, as WinForms does. public PlateEdits Edits { get; } /// /// Opens one undoable edit of the shown nest (its tab's history); unset, edits are not /// recorded. /// public Func BeginChangeHandler { get; set; } /// The nest's settings that cut-offs regenerate with after an edit. public CutOffSettings CutOffSettings { get; set; } = new(); /// No edits while Auto Nest works on the nest (WinForms EditsLocked). public bool EditsLocked { get; set; } /// /// Which way Shift+click and Ctrl+click settle a placed copy (Tools > Options > Clone /// push placement), read at each click. /// public Func PlacementOrder { get; set; } = () => SettleOrder.ClosestToCorner; /// /// Edit > Copy: places copies of the selected parts with the place tool; false when /// nothing is selected or edits are locked. /// public bool CopySelection() => PlateClipboard.Copy(this, tools, ReadPlacementOrder) != null; /// /// Edit > Cut: as , then removes the parts as one Cut step. /// public bool CutSelection() => PlateClipboard.Cut(this, tools, ReadPlacementOrder) != null; /// /// A drawing picked in the drawing list and carried into the view: the place tool with one /// new part of it. /// public void PlaceDrawing(Drawing drawing) => tools.SetTool(DrawingPlacement.CreatePlaceTool(this, drawing, ReadPlacementOrder)); /// /// A drawing dragged from the drawing list and dropped at (view /// coordinates): one part centred there, or null while edits are locked. /// public Part DropDrawing(Drawing drawing, Point at) => DrawingPlacement.AddPart(this, drawing, ToWorld(at)); private SettleOrder ReadPlacementOrder() => PlacementOrder?.Invoke() ?? SettleOrder.ClosestToCorner; Undo.ChangeScope IPlateToolHost.BeginChange(string label, object coalesceKey) => BeginChangeHandler?.Invoke(label, coalesceKey) ?? Undo.ChangeScope.Detached(); /// The cursor in plate coordinates, or null when it is outside the view. public Vector? CursorWorld { get; private set; } /// Pixels per drawing unit. public double Zoom => view.Scale; /// The view's world/screen mapping. public ViewTransform View => view; public event EventHandler ViewChanged; public PlateCanvas() { ClipToBounds = true; Focusable = true; hitTester = new PlateHitTester(part => PathsFor(part).Geometry); tools = new PlateToolManager(this); // While the place tool is active, edits move its copies. Edits = new PlateEdits(this) { Tools = tools }; selection.Changed += (_, _) => { InvalidateVisual(); ViewChanged?.Invoke(this, EventArgs.Empty); }; tools.StatusChanged += (_, _) => { // A place tool's copies leave the cache when the tool ends. TrimCache(); ViewChanged?.Invoke(this, EventArgs.Empty); }; } void IPlateToolHost.Invalidate() => InvalidateVisual(); /// Edit > Select All: every part on the plate, cut-off segments excepted. public void SelectAll() => selection.SelectAll(); public void ClearCache() { paths.Clear(); labelPoints.Clear(); commonLineChecks.Clear(); } // Keeps only the shown plate's parts and the place tool's copies, so closed plates and // ended tools do not hold their paths. private void TrimCache() { if (plate == null) { paths.Clear(); labelPoints.Clear(); return; } var shown = new HashSet(plate.Parts); if (tools?.Current is PlaceTool place) shown.UnionWith(place.Previews); foreach (var stale in paths.Keys.Where(part => !shown.Contains(part)).ToList()) paths.Remove(stale); var drawings = new HashSet(plate.Parts.Select(part => part.BaseDrawing)); foreach (var stale in labelPoints.Keys.Where(drawing => !drawings.Contains(drawing)).ToList()) labelPoints.Remove(stale); } public void ZoomToFit() { if (!Fit()) return; InvalidateVisual(); ViewChanged?.Invoke(this, EventArgs.Empty); } /// Fits the view to the plate and its parts without requesting a redraw. private bool Fit() { if (plate == null || Bounds.Width <= 0 || Bounds.Height <= 0) return false; view.Resize(Bounds.Width, Bounds.Height); if (!view.ZoomToArea(plate.BoundingBox(true))) return false; fitPending = false; return true; } private Vector ToWorld(Point p) => view.ScreenToWorld(p.X, p.Y); private SKMatrix WorldMatrix => new((float)view.Scale, 0, (float)view.OriginX, 0, (float)-view.Scale, (float)view.OriginY, 0, 0, 1); private PartPaths PathsFor(Part part) { if (!paths.TryGetValue(part, out var result) || !result.Geometry.IsCurrentFor(part)) paths[part] = result = PartPaths.Build(part); return result; } private Vector LabelPoint(Part part) { if (PartLabels.CutOffSegmentPoint(part) is { } cutOff) return cutOff; var drawing = part.BaseDrawing; if (!labelPoints.TryGetValue(drawing, out var cached) || !ReferenceEquals(cached.Program, drawing.Program) || cached.Rotation != drawing.Program.Rotation) { cached = (drawing.Program, drawing.Program.Rotation, PartLabels.LabelPoint(drawing)); labelPoints[drawing] = cached; } return PartLabels.Place(part, cached.Point); } private SKPath OffsetFor(Part part, double spacing, double tolerance) { if (offsets.TryGetValue(part, out var entry) && ReferenceEquals(entry.Program, part.Program) && entry.Rotation == part.Rotation && entry.Spacing == spacing && entry.Tolerance == tolerance) return entry.Path; var polygons = PlateOverlays.OffsetOutline(part, spacing, tolerance); var path = SkiaFigures.Polygons(polygons.Select(p => (IReadOnlyList)p.Vertices)); offsets.AddOrUpdate(part, new OffsetEntry(part.Program, part.Rotation, spacing, tolerance, path)); return path; } public override void Render(DrawingContext context) { // A redraw may not be requested during a render, so tell listeners afterwards. if (fitPending && Fit()) global::Avalonia.Threading.Dispatcher.UIThread.Post(() => ViewChanged?.Invoke(this, EventArgs.Empty)); if (Bounds.Width > 0 && Bounds.Height > 0) view.Resize(Bounds.Width, Bounds.Height); var scene = new Scene { Bounds = new Rect(Bounds.Size), Palette = SkiaSchemePalette.For(Scheme ?? ColorScheme.Default), Matrix = WorldMatrix, Scale = view.Scale, DrawOrigin = Options.DrawOrigin, }; if (plate != null) BuildScene(scene); context.Custom(new PlateDrawOperation(scene)); } private void BuildScene(Scene scene) { var options = Options; var visible = view.VisibleWorld(); scene.Sheet = PlateOverlays.Sheet(plate); if (plate.Outline is { } outline) { scene.SheetOutline = SkiaFigures.Polygons(new[] { PlateOverlays.PlaceOutline(plate, outline.Points) } .Concat(outline.Obstacles.Select(o => PlateOverlays.PlaceOutline(plate, o)))); scene.Obstacles = outline.Obstacles.Count == 0 ? null : SkiaFigures.Polygons(outline.Obstacles.Select(o => PlateOverlays.PlaceOutline(plate, o))); var usable = PlateOverlays.UsableOutline(plate); scene.Usable = usable.Count == 0 ? null : SkiaFigures.Polygons(usable); } else { var edge = PlateOverlays.EdgeSpacing(plate); // As WinForms: the edge-spacing line is left out while it surrounds the whole view. if (!Contains(edge, visible)) scene.EdgeSpacing = edge; } var palette = scene.Palette; for (var i = 0; i < plate.Parts.Count; i++) { var part = plate.Parts[i]; var partPaths = PathsFor(part); var bounds = partPaths.StrokeBounds; var placed = bounds == null ? null : bounds.Translate(part.Location.X, part.Location.Y); if (placed == null || !Intersects(placed, visible)) continue; var color = ToSkColor(part.BaseDrawing.Color); scene.Parts.Add(new PartItem(partPaths, part.Location, placed, color, palette.PartOutline(color), (i + 1).ToString(), LabelPoint(part), selection.Contains(part), ReferenceEquals(part, HoveredPart), part.BaseDrawing.IsCutOff)); } // The place tool's copies, drawn selected and unnumbered over the plate, as WinForms. if (tools.Current is PlaceTool { Previews: var previews }) { foreach (var preview in previews) { var bounds = PathsFor(preview).StrokeBounds; if (bounds == null) continue; var placed = bounds.Translate(preview.Location.X, preview.Location.Y); var color = ToSkColor(preview.BaseDrawing.Color); scene.Parts.Add(new PartItem(PathsFor(preview), preview.Location, placed, color, palette.PartOutline(color), Label: null, preview.Location, Selected: true, Hovered: false, IsCutOff: false)); } } if (options.DrawOffset && plate.PartSpacing > 0) { foreach (var part in plate.Parts) scene.Offsets.Add((OffsetFor(part, plate.PartSpacing, options.OffsetTolerance), part.Location)); } if (options.DrawBounds) scene.SelectionBounds = PlateOverlays.SelectionBounds(selection.Parts.Where(plate.Parts.Contains)); if (options.DrawRapid) scene.Rapids = PlateOverlays.Rapids(plate); if (options.DrawPiercePoints) scene.PiercePoints = PlateOverlays.PiercePoints(plate); if (options.DrawCutDirection) scene.Arrows = PlateOverlays.CutDirection(plate, view.LengthToWorld(60)); scene.Clamps = PlateOverlays.Clamps(plate); scene.RemovedClamps = PlateOverlays.RemovedClamps(plate); BuildCutOffs(scene); if (tools.Current is SelectTool { Window: { } window }) scene.Window = window; BuildCommonLines(scene); if (options.DrawSupport) BuildSupport(scene); } // A selected cut-off is drawn solid blue in place of its dashes, as in WinForms. private void BuildCutOffs(Scene scene) { foreach (var cutOff in plate.CutOffs) { var program = cutOff.Drawing?.Program; if (program == null || program.Codes.Count == 0) continue; var strokes = selection.Contains(cutOff) ? scene.SelectedCutOffStrokes : scene.CutOffStrokes; strokes.AddRange(CutOff.CutStrokes(program, Vector.Zero)); } } private void BuildCommonLines(Scene scene) { if (plate.CommonLines is not { Count: > 0 } groups) { commonLineChecks.Clear(); return; } foreach (var stale in commonLineChecks.Keys.Where(group => !groups.Contains(group)).ToList()) commonLineChecks.Remove(stale); foreach (var group in groups) { var state = string.Join(";", group.Members.Select(m => $"{m.Location.X:R},{m.Location.Y:R},{m.Rotation:R},{RuntimeHelpers.GetHashCode(m.BaseDrawing.Program)}")); if (!commonLineChecks.TryGetValue(group, out var cached) || cached.State != state) { cached = (state, CommonLineGeometry.Check(group)); commonLineChecks[group] = cached; } foreach (var path in CommonLineGeometry.Paths(cached.Check.Spans, group.Kerf)) scene.CommonLines.Add(path.Points); foreach (var problem in cached.Check.Problems) { // A copy: moving the part changes its box in place while the render thread draws. var box = problem.Part.BoundingBox; scene.CommonLineProblems.Add(new Box(box.X, box.Y, box.Length, box.Width)); } } } private void BuildSupport(Scene scene) { if (plate.SupportBed is not { } bed) return; // Grid points and slats only while they are at least 6 pixels apart on screen. const double minimumSpacing = 6; if (bed is SupportGrid grid && view.LengthToScreen(System.Math.Min(grid.PitchX, grid.PitchY)) >= minimumSpacing) scene.GridPoints = grid.PointsIn(scene.Sheet, plate.Quadrant); else if (bed is SupportSlats slats && view.LengthToScreen(slats.Pitch) >= minimumSpacing) scene.Slats = slats.SlatsIn(scene.Sheet, plate.Quadrant); var clearance = PlateOverlays.SupportClearance(plate); foreach (var part in plate.Parts) { var support = supports.Analyze(part, bed, plate.Quadrant, clearance); if (support is not { IsComplete: true }) continue; scene.Supports.Add(new SupportItem(support.Contacts, support.CenterOfGravity, support.IsSupported, support.IsSupported ? null : support.BestTabPoint)); } } private static bool Contains(Box outer, Box inner) => inner.Left >= outer.Left && inner.Right <= outer.Right && inner.Bottom >= outer.Bottom && inner.Top <= outer.Top; private static bool Intersects(Box a, Box b) => a.Left <= b.Right && a.Right >= b.Left && a.Bottom <= b.Top && a.Top >= b.Bottom; private static SKColor ToSkColor(System.Drawing.Color color) => color.IsEmpty ? new SKColor(130, 204, 130) : new SKColor(color.R, color.G, color.B, color.A); protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { // As WinForms: Shift+wheel turns the selection (Ctrl+Shift by a tenth); without a // selection the wheel zooms. Some platforms report Shift+wheel as horizontal. if (e.KeyModifiers.HasFlag(KeyModifiers.Shift) && Edits.HasPartsToEdit && !EditsLocked) { var delta = e.Delta.Y != 0 ? e.Delta.Y : e.Delta.X; Edits.RotateByWheel( (int)System.Math.Truncate(delta), fine: IsControl(e.KeyModifiers)); e.Handled = true; return; } var at = e.GetPosition(this); view.ZoomAt(new ScreenPoint(at.X, at.Y), System.Math.Pow(1.2, e.Delta.Y)); InvalidateVisual(); ViewChanged?.Invoke(this, EventArgs.Empty); e.Handled = true; } protected override void OnPointerPressed(PointerPressedEventArgs e) { Focus(); var point = e.GetCurrentPoint(this); var properties = point.Properties; if (properties.IsMiddleButtonPressed) { // As WinForms: a middle double-click fits only with nothing selected; with a // selection each click turns it, so a double-click turns it 180 degrees. if (e.ClickCount == 2 && (EditsLocked || !Edits.HasPartsToEdit)) { ZoomToFit(); return; } panStart = point.Position; middleDown = point.Position; e.Pointer.Capture(this); return; } var button = properties.IsLeftButtonPressed ? ToolButton.Left : properties.IsRightButtonPressed ? ToolButton.Right : ToolButton.None; if (button == ToolButton.None) return; ClearHover(); if (tools.Current.PointerPressed(ToolPointerAt(point.Position, button, e.KeyModifiers))) e.Handled = true; if (button == ToolButton.Left) e.Pointer.Capture(this); } protected override void OnPointerMoved(PointerEventArgs e) { var point = e.GetCurrentPoint(this); var at = point.Position; CursorWorld = ToWorld(at); if (panStart is { } start) { view.Pan(at.X - start.X, at.Y - start.Y); panStart = at; InvalidateVisual(); } else { var button = point.Properties.IsLeftButtonPressed ? ToolButton.Left : point.Properties.IsRightButtonPressed ? ToolButton.Right : ToolButton.None; tools.Current.PointerMoved(ToolPointerAt(at, button, e.KeyModifiers)); // As WinForms: the part under the cursor is highlighted only in Select, while no // button is held. var hovered = button == ToolButton.None && tools.Current is SelectTool ? hitTester.PartAt(plate, CursorWorld.Value) : null; if (!ReferenceEquals(hovered, HoveredPart)) { HoveredPart = hovered; InvalidateVisual(); } } ViewChanged?.Invoke(this, EventArgs.Empty); } protected override void OnPointerReleased(PointerReleasedEventArgs e) { var button = e.InitialPressMouseButton switch { MouseButton.Left => ToolButton.Left, MouseButton.Right => ToolButton.Right, MouseButton.Middle => ToolButton.Middle, _ => ToolButton.None, }; if (button == ToolButton.Middle) { panStart = null; // A middle click, not a drag, turns the selection 90 degrees. var at = e.GetPosition(this); if (middleDown is { } down && Edits.HasPartsToEdit && (at.X - down.X) * (at.X - down.X) + (at.Y - down.Y) * (at.Y - down.Y) < 25) Edits.RotateQuarterTurn(); middleDown = null; } else if (button != ToolButton.None && tools.Current.PointerReleased(ToolPointerAt(e.GetPosition(this), button, e.KeyModifiers))) e.Handled = true; // Kept while another button is still down: a middle click during a left drag must // not end the drag. var held = e.GetCurrentPoint(this).Properties; if (!held.IsLeftButtonPressed && !held.IsMiddleButtonPressed && !held.IsRightButtonPressed) e.Pointer.Capture(null); } // The pointer was taken away mid-gesture (Alt+Tab during a drag): the tool ends what it // was doing, and a pan or middle click stops. protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) { base.OnPointerCaptureLost(e); panStart = null; middleDown = null; tools.Current.PointerCaptureLost(); } // As the WinForms plate view: the pointer entering the view gives it the keyboard, which // also places a drawing picked up in the drawing list. protected override void OnPointerEntered(PointerEventArgs e) { base.OnPointerEntered(e); if (!IsFocused) Focus(); } protected override void OnPointerExited(PointerEventArgs e) { CursorWorld = null; ClearHover(); ViewChanged?.Invoke(this, EventArgs.Empty); } private void ClearHover() { if (HoveredPart == null) return; HoveredPart = null; InvalidateVisual(); } private ToolPointer ToolPointerAt(Point at, ToolButton button, KeyModifiers keys) => new(ToWorld(at), new ScreenPoint(at.X, at.Y), button, ModifiersOf(keys)); private static ToolModifiers ModifiersOf(KeyModifiers keys) { var modifiers = ToolModifiers.None; if (keys.HasFlag(KeyModifiers.Shift)) modifiers |= ToolModifiers.Shift; // Command on macOS stands in for Ctrl, as Avalonia's own gestures do. if (IsControl(keys)) modifiers |= ToolModifiers.Control; if (keys.HasFlag(KeyModifiers.Alt)) modifiers |= ToolModifiers.Alt; return modifiers; } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Escape && e.KeyModifiers == KeyModifiers.None) { tools.Escape(); e.Handled = true; } else if (e.Key == Key.F && e.KeyModifiers == KeyModifiers.None) { ZoomToFit(); e.Handled = true; } else if (e.Key is Key.Enter or Key.F1 && tools.Current is PlaceTool place) { // As WinForms: Enter and F1 place a copy, Shift or Ctrl held settling it. place.Apply(ModifiersOf(e.KeyModifiers)); e.Handled = true; } else if (EditFor(e.Key, e.KeyModifiers) is { } edit) { edit(); e.Handled = true; } } private static bool IsControl(KeyModifiers keys) => keys.HasFlag(KeyModifiers.Control) || keys.HasFlag(KeyModifiers.Meta); // The WinForms plate view's editing keys: Delete; arrows nudge; Shift+arrows, X, Shift+X, // Shift+Y and Y push to contact. private Action EditFor(Key key, KeyModifiers modifiers) => (key, modifiers) switch { // WinForms deletes on the Delete key whatever modifiers are held. (Key.Delete, _) => Edits.Delete, (Key.Left, KeyModifiers.None) => () => Edits.Nudge(PushDirection.Left), (Key.Right, KeyModifiers.None) => () => Edits.Nudge(PushDirection.Right), (Key.Up, KeyModifiers.None) => () => Edits.Nudge(PushDirection.Up), (Key.Down, KeyModifiers.None) => () => Edits.Nudge(PushDirection.Down), (Key.Left, KeyModifiers.Shift) or (Key.X, KeyModifiers.None) => () => Edits.Push(PushDirection.Left), (Key.Right, KeyModifiers.Shift) or (Key.X, KeyModifiers.Shift) => () => Edits.Push(PushDirection.Right), (Key.Up, KeyModifiers.Shift) or (Key.Y, KeyModifiers.Shift) => () => Edits.Push(PushDirection.Up), (Key.Down, KeyModifiers.Shift) or (Key.Y, KeyModifiers.None) => () => Edits.Push(PushDirection.Down), _ => null, }; protected override void OnSizeChanged(global::Avalonia.Controls.SizeChangedEventArgs e) { base.OnSizeChanged(e); view.Resize(e.NewSize.Width, e.NewSize.Height); InvalidateVisual(); } private sealed record PartItem(PartPaths Paths, Vector Location, Box Bounds, SKColor Color, SKColor Outline, string Label, Vector LabelPoint, bool Selected, bool Hovered, bool IsCutOff); private sealed record SupportItem(IReadOnlyList Contacts, Vector CenterOfGravity, bool Supported, Vector? Tab); /// Everything one frame draws, built on the UI thread and only read on the render thread. private sealed class Scene { public Rect Bounds; public SkiaSchemePalette Palette; public SKMatrix Matrix; public double Scale; public bool DrawOrigin; public Box Sheet; public SKPath SheetOutline; public SKPath Obstacles; public SKPath Usable; public Box EdgeSpacing; public readonly List Parts = new(); public readonly List<(SKPath Path, Vector Location)> Offsets = new(); public Box SelectionBounds; public IReadOnlyList Rapids; public IReadOnlyList PiercePoints; public IReadOnlyList Arrows; public IReadOnlyList Clamps; public IReadOnlyList RemovedClamps; public readonly List CutOffStrokes = new(); public readonly List SelectedCutOffStrokes = new(); public SelectionWindow? Window; public readonly List> CommonLines = new(); public readonly List CommonLineProblems = new(); public IReadOnlyList GridPoints; public IReadOnlyList Slats; public readonly List Supports = new(); } private sealed class PlateDrawOperation : ICustomDrawOperation { private readonly Scene scene; public PlateDrawOperation(Scene scene) { this.scene = scene; } public Rect Bounds => scene.Bounds; public bool HitTest(Point p) => Bounds.Contains(p); public bool Equals(ICustomDrawOperation other) => false; public void Dispose() { } public void Render(ImmediateDrawingContext context) { var lease = context.TryGetFeature(); if (lease == null) return; using var api = lease.Lease(); var canvas = api.SkCanvas; canvas.Save(); canvas.ClipRect(new SKRect(0, 0, (float)Bounds.Width, (float)Bounds.Height)); canvas.Clear(scene.Palette.Background); new PlatePainter(canvas, scene).Paint(); canvas.Restore(); } } /// /// Paints a scene in the WinForms view's order and pen sizes: widths and dashes are screen /// pixels, so parts drawn in world units scale them by the zoom. /// private sealed class PlatePainter { private static readonly SKColor LeadColor = new(255, 69, 0); // OrangeRed private static readonly SKColor DisplayColor = new(70, 110, 140); private static readonly SKColor OffsetColor = new(255, 100, 100, 120); private static readonly SKColor CutDirectionColor = new(60, 60, 60); private static readonly SKColor PierceFill = new(255, 0, 0); private static readonly SKColor PierceOutline = new(139, 0, 0); // DarkRed private static readonly SKColor ClampHatch = new(70, 80, 90, 150); private static readonly SKColor ClampBack = new(230, 170, 40, 70); private static readonly SKColor ClampOutline = new(150, 100, 0, 220); private static readonly SKColor RemovedClampOutline = new(110, 110, 110, 200); private static readonly SKColor ObstacleHatch = new(120, 60, 60, 170); private static readonly SKColor ObstacleBack = new(200, 80, 80, 60); private static readonly SKColor CutOffColor = new(255, 69, 0); // OrangeRed private static readonly SKColor SelectedCutOffColor = new(0, 120, 255); private static readonly SKColor WindowContainsBorder = new(99, 162, 228); private static readonly SKColor WindowContainsFill = new(150, 200, 255, 90); private static readonly SKColor WindowIntersectBorder = new(50, 255, 50); private static readonly SKColor WindowIntersectFill = new(50, 255, 50, 50); private static readonly SKColor CommonLineColor = new(0, 150, 136); private static readonly SKColor BrokenCommonLineColor = new(255, 0, 0); private static readonly SKColor GridColor = new(120, 120, 120, 110); private static readonly SKColor SlatColor = new(120, 120, 120, 90); private static readonly SKColor ContactColor = new(30, 150, 60, 220); private static readonly SKColor SupportedColor = new(20, 140, 50, 230); private static readonly SKColor TippingColor = new(210, 30, 30, 240); private static readonly SKColor TabColor = new(240, 140, 0, 240); // The WinForms default font, bold and underlined, for part numbers. private static readonly SKTypeface LabelTypeface = SKTypeface.FromFamilyName(null, SKFontStyle.Bold) ?? SKTypeface.Default; private readonly SKCanvas canvas; private readonly Scene scene; // Not readonly: SKCanvas.Concat takes it by reference. private SKMatrix matrix; private readonly float scale; public PlatePainter(SKCanvas canvas, Scene scene) { this.canvas = canvas; this.scene = scene; matrix = scene.Matrix; scale = (float)scene.Scale; } private SKPoint Screen(Vector world) => matrix.MapPoint((float)world.X, (float)world.Y); private SKRect Screen(Box box) { var a = Screen(new Vector(box.Left, box.Top)); var b = Screen(new Vector(box.Right, box.Bottom)); return new SKRect(System.Math.Min(a.X, b.X), System.Math.Min(a.Y, b.Y), System.Math.Max(a.X, b.X), System.Math.Max(a.Y, b.Y)); } private static SKPaint Stroke(SKColor color, float width = 1, float[] dash = null) => new() { Style = SKPaintStyle.Stroke, Color = color, StrokeWidth = width, IsAntialias = true, PathEffect = dash == null ? null : SKPathEffect.CreateDash(dash, 0), }; private static SKPaint Fill(SKColor color) => new() { Style = SKPaintStyle.Fill, Color = color, IsAntialias = true }; // A pen of screen width in the world frame: width 1 stays a one-pixel hairline. private SKPaint WorldStroke(SKColor color, float width = 1, float[] dash = null) => Stroke(color, width <= 1 && dash == null ? 0 : width / scale, dash?.Select(d => d / scale).ToArray()); public void Paint() { if (scene.DrawOrigin) { using var origin = Stroke(scene.Palette.Origin); origin.IsAntialias = false; var o = Screen(Vector.Zero); canvas.DrawLine(o.X, 0, o.X, (float)scene.Bounds.Height, origin); canvas.DrawLine(0, o.Y, (float)scene.Bounds.Width, o.Y, origin); } if (scene.Sheet == null) return; DrawSheet(); DrawParts(); DrawOffsets(); if (scene.SelectionBounds != null) { using var pen = Stroke(scene.Palette.BoundingBox); canvas.DrawRect(Screen(scene.SelectionBounds), pen); } DrawRapids(); DrawPiercePoints(); DrawCutDirection(); DrawClamps(); DrawCutOffs(); DrawCommonLines(); DrawSupport(); DrawSelectionWindow(); } private void DrawSheet() { var palette = scene.Palette; canvas.Save(); canvas.Concat(ref matrix); using var sheetFill = Fill(palette.PlateFill); if (scene.SheetOutline != null) { canvas.DrawPath(scene.SheetOutline, sheetFill); canvas.Restore(); if (scene.Obstacles != null) { HatchPath(scene.Obstacles, ObstacleHatch, ObstacleBack); using var obstaclePen = WorldStroke(ObstacleHatch, 1.5f); DrawWorld(scene.Obstacles, obstaclePen); } if (scene.Usable != null) { using var usablePen = WorldStroke(palette.EdgeSpacing, 1, new float[] { 3, 3 }); DrawWorld(scene.Usable, usablePen); } using var outlinePen = WorldStroke(palette.PlateOutline); DrawWorld(scene.SheetOutline, outlinePen); return; } var sheet = scene.Sheet; canvas.DrawRect(new SKRect((float)sheet.Left, (float)sheet.Bottom, (float)sheet.Right, (float)sheet.Top), sheetFill); canvas.Restore(); if (scene.EdgeSpacing != null) { using var edgePen = Stroke(palette.EdgeSpacing, 1, new float[] { 3, 3 }); edgePen.IsAntialias = false; canvas.DrawRect(Screen(scene.EdgeSpacing), edgePen); } using var outline = Stroke(palette.PlateOutline); outline.IsAntialias = false; canvas.DrawRect(Screen(sheet), outline); } private void DrawWorld(SKPath path, SKPaint paint) { canvas.Save(); canvas.Concat(ref matrix); canvas.DrawPath(path, paint); canvas.Restore(); } // GDI+ WideUpwardDiagonal: three-pixel "/" stripes every eight pixels, in screen space. private void HatchPath(SKPath worldPath, SKColor hatch, SKColor back) { using var screenPath = new SKPath(worldPath); screenPath.Transform(matrix); using var shader = HatchShader(hatch, back); using var paint = new SKPaint { Style = SKPaintStyle.Fill, Shader = shader }; canvas.DrawPath(screenPath, paint); } private void HatchRect(SKRect rect, SKColor hatch, SKColor back) { using var shader = HatchShader(hatch, back); using var paint = new SKPaint { Style = SKPaintStyle.Fill, Shader = shader }; canvas.DrawRect(rect, paint); } private static SKShader HatchShader(SKColor hatch, SKColor back) { using var bitmap = new SKBitmap(8, 8, SKColorType.Rgba8888, SKAlphaType.Unpremul); for (var y = 0; y < 8; y++) for (var x = 0; x < 8; x++) bitmap.SetPixel(x, y, (x + y) % 8 < 3 ? hatch : back); return SKShader.CreateBitmap(bitmap, SKShaderTileMode.Repeat, SKShaderTileMode.Repeat); } private void DrawParts() { var palette = scene.Palette; using var fill = Fill(SKColors.Black); using var cut = WorldStroke(SKColors.Black); using var etch = WorldStroke(palette.Etch, 1.5f); using var lead = WorldStroke(LeadColor, 1.5f); using var display = WorldStroke(DisplayColor, 1, new float[] { 6, 3 }); using var text = new SKPaint { Color = SKColors.Black, IsAntialias = true, TextSize = 11, Typeface = LabelTypeface, TextAlign = SKTextAlign.Center, }; using var underline = Stroke(SKColors.Black); var metrics = text.FontMetrics; var textHeight = metrics.Descent - metrics.Ascent; foreach (var item in scene.Parts) { canvas.Save(); canvas.Concat(ref matrix); canvas.Translate((float)item.Location.X, (float)item.Location.Y); fill.Color = item.Selected ? palette.SelectedFill : item.Hovered ? Lighten(item.Color) : item.Color; canvas.DrawPath(item.Paths.Material, fill); if (item.Paths.Display != null) canvas.DrawPath(item.Paths.Display, display); canvas.DrawPath(item.Paths.Etch, etch); // Keep real cuts visible even where an etch overlaps them. cut.Color = item.Selected ? palette.SelectedOutline : item.Outline; canvas.DrawPath(item.Paths.Cut, cut); // As on the desktop, only manually placed lead-ins are shown. canvas.DrawPath(item.Paths.Lead, lead); canvas.Restore(); // A number shows only once the part is big enough on screen to hold it. if (item.IsCutOff || item.Label == null) continue; var bounds = Screen(item.Bounds); var width = text.MeasureText(item.Label); if (bounds.Width < width || bounds.Height < textHeight) continue; var at = Screen(item.LabelPoint); var baseline = at.Y - (metrics.Ascent + metrics.Descent) / 2; canvas.DrawText(item.Label, at.X, baseline, text); var lineY = baseline + System.Math.Max(1, metrics.UnderlinePosition ?? 1.5f); canvas.DrawLine(at.X - width / 2, lineY, at.X + width / 2, lineY, underline); } } private void DrawOffsets() { if (scene.Offsets.Count == 0) return; using var pen = WorldStroke(OffsetColor); foreach (var (path, location) in scene.Offsets) { canvas.Save(); canvas.Concat(ref matrix); canvas.Translate((float)location.X, (float)location.Y); canvas.DrawPath(path, pen); canvas.Restore(); } } private void DrawRapids() { if (scene.Rapids == null) return; using var pen = Stroke(scene.Palette.Rapid, 1, new float[] { 10, 10 }); foreach (var segment in scene.Rapids) canvas.DrawLine(Screen(segment.From), Screen(segment.To), pen); } private void DrawPiercePoints() { if (scene.PiercePoints == null) return; using var fill = Fill(PierceFill); using var pen = Stroke(PierceOutline); foreach (var point in scene.PiercePoints) { var p = Screen(point); canvas.DrawCircle(p, 2, fill); canvas.DrawCircle(p, 2, pen); } } private void DrawCutDirection() { if (scene.Arrows == null) return; const float size = 6; using var pen = Stroke(CutDirectionColor, 1.5f); foreach (var sample in scene.Arrows) { var tip = Screen(sample.Position); // Screen space flips Y, so the screen angle mirrors the world tangent. var angle = System.Math.Atan2(-sample.Direction.Y, sample.Direction.X); foreach (var side in new[] { 0.5, -0.5 }) { var a = angle + System.Math.PI + side; canvas.DrawLine(tip.X + size * (float)System.Math.Cos(a), tip.Y + size * (float)System.Math.Sin(a), tip.X, tip.Y, pen); } } } // Machine clamps are fixtures, not material: a translucent hatched amber keep-out. private void DrawClamps() { using var outline = Stroke(ClampOutline, 1.5f); foreach (var clamp in scene.Clamps) { var rect = Screen(clamp); HatchRect(rect, ClampHatch, ClampBack); canvas.DrawRect(rect, outline); } using var removed = Stroke(RemovedClampOutline, 1.5f, new float[] { 4.5f, 1.5f }); using var text = new SKPaint { Color = RemovedClampOutline, IsAntialias = true, TextSize = 9 }; foreach (var clamp in scene.RemovedClamps) { var rect = Screen(clamp); canvas.DrawRect(rect, removed); canvas.DrawText("remove", rect.Left, rect.Top - text.FontMetrics.Descent, text); } } // Scrap cut-off lines stand out from the dark part outlines: a saturated orange-red dash. private void DrawCutOffs() { using var pen = Stroke(CutOffColor, 2, new float[] { 6, 2 }); foreach (var stroke in scene.CutOffStrokes) canvas.DrawLine(Screen(stroke.StartPoint), Screen(stroke.EndPoint), pen); using var selectedPen = Stroke(SelectedCutOffColor, 3.5f); foreach (var stroke in scene.SelectedCutOffStrokes) canvas.DrawLine(Screen(stroke.StartPoint), Screen(stroke.EndPoint), selectedPen); // Each segment's number over the line, on a disc of the line's colour. using var disc = Fill(CutOffColor); using var text = new SKPaint { Color = SKColors.White, IsAntialias = true, TextSize = 11, Typeface = LabelTypeface, TextAlign = SKTextAlign.Center, }; var metrics = text.FontMetrics; var textHeight = metrics.Descent - metrics.Ascent; foreach (var item in scene.Parts) { if (!item.IsCutOff) continue; var bounds = Screen(item.Bounds); var diameter = System.Math.Max(text.MeasureText(item.Label), textHeight) + 2; if (System.Math.Max(bounds.Width, bounds.Height) < diameter) continue; var at = Screen(item.LabelPoint); canvas.DrawCircle(at, diameter / 2, disc); canvas.DrawText(item.Label, at.X, at.Y - (metrics.Ascent + metrics.Descent) / 2, text); } } // The Select tool's window: blue while it selects what it contains, green while it // selects what it touches, in the WinForms colours. private void DrawSelectionWindow() { if (scene.Window is not { } window) return; var contains = window.Mode == WindowSelectionMode.Contains; var rect = Screen(window.Box); using var fill = Fill(contains ? WindowContainsFill : WindowIntersectFill); fill.IsAntialias = false; canvas.DrawRect(rect, fill); using var border = Stroke(contains ? WindowContainsBorder : WindowIntersectBorder); border.IsAntialias = false; canvas.DrawRect(rect, border); } private void DrawCommonLines() { using var pen = Stroke(CommonLineColor, 2, new float[] { 6, 2 }); foreach (var points in scene.CommonLines) for (var i = 1; i < points.Count; i++) canvas.DrawLine(Screen(points[i - 1]), Screen(points[i]), pen); using var broken = Stroke(BrokenCommonLineColor, 2); foreach (var box in scene.CommonLineProblems) canvas.DrawRect(Screen(box), broken); } private void DrawSupport() { if (scene.GridPoints != null) { // Whole-pixel squares, not anti-aliased dots, so every point is the same size. using var grid = new SKPaint { Style = SKPaintStyle.Fill, Color = GridColor, IsAntialias = false }; foreach (var point in scene.GridPoints) { var p = Screen(point); var x = (float)System.Math.Round(p.X) - 1; var y = (float)System.Math.Round(p.Y) - 1; canvas.DrawRect(x, y, 3, 3, grid); } } if (scene.Slats != null) { using var slat = new SKPaint { Style = SKPaintStyle.Fill, Color = SlatColor, IsAntialias = false }; foreach (var box in scene.Slats) { var rect = Screen(box); // At least a pixel wide however far out the view is. if (rect.Width < 1) rect = new SKRect(rect.MidX - 0.5f, rect.Top, rect.MidX + 0.5f, rect.Bottom); if (rect.Height < 1) rect = new SKRect(rect.Left, rect.MidY - 0.5f, rect.Right, rect.MidY + 0.5f); canvas.DrawRect(rect, slat); } } using var contact = Fill(ContactColor); using var supported = Stroke(SupportedColor, 2); using var tipping = Stroke(TippingColor, 2); using var tab = Fill(TabColor); foreach (var item in scene.Supports) { foreach (var point in item.Contacts) canvas.DrawCircle(Screen(point), 2.5f, contact); const float size = 6; var c = Screen(item.CenterOfGravity); var pen = item.Supported ? supported : tipping; canvas.DrawCircle(c, size, pen); canvas.DrawLine(c.X - size, c.Y, c.X + size, c.Y, pen); canvas.DrawLine(c.X, c.Y - size, c.X, c.Y + size, pen); if (item.Tab is { } point2) { const float d = 5; var t = Screen(point2); using var diamond = new SKPath(); diamond.MoveTo(t.X, t.Y - d); diamond.LineTo(t.X + d, t.Y); diamond.LineTo(t.X, t.Y + d); diamond.LineTo(t.X - d, t.Y); diamond.Close(); canvas.DrawPath(diamond, tab); } } } private static SKColor Lighten(SKColor c) => new((byte)(c.Red + (255 - c.Red) / 2), (byte)(c.Green + (255 - c.Green) / 2), (byte)(c.Blue + (255 - c.Blue) / 2), c.Alpha); } } }