using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Titano.Core.Localization;
namespace Titano.Ui.Visuals;
///
/// Per-frame line chart of the editor (BRIEF §12.3: measured luminance in Sun, target curve in Accent, sky region
/// dashed in Region…). Draws a legend row (series titles or , plus a right-aligned
/// ), gridlines on nice Y ticks with labels, dashed vertical markers, and every series
/// decimated to at most two points per device-pixel column so 100k+ frames stay fast. The playhead follows
/// ; clicking or dragging in the plot seeks; hovering shows a crosshair, dots on the
/// series and a readout tooltip with the values under the cursor. The Y range is automatic with padding unless
/// / are set.
///
public sealed class SeriesChart : DrawingElement
{
public static readonly DependencyProperty SeriesProperty = DependencyProperty.Register(
nameof(Series), typeof(IReadOnlyList), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged));
public static readonly DependencyProperty MarkersProperty = DependencyProperty.Register(
nameof(Markers), typeof(IReadOnlyList), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged));
public static readonly DependencyProperty LegendProperty = DependencyProperty.Register(
nameof(Legend), typeof(IReadOnlyList), typeof(SeriesChart), new PropertyMetadata(null, OnDataPropertyChanged));
public static readonly DependencyProperty SummaryProperty = DependencyProperty.Register(
nameof(Summary), typeof(string), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty ShowLegendProperty = DependencyProperty.Register(
nameof(ShowLegend), typeof(bool), typeof(SeriesChart), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty ShowYLabelsProperty = DependencyProperty.Register(
nameof(ShowYLabels), typeof(bool), typeof(SeriesChart), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty CurrentIndexProperty = DependencyProperty.Register(
nameof(CurrentIndex), typeof(int), typeof(SeriesChart),
new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnOverlayPropertyChanged));
public static readonly DependencyProperty IsSeekEnabledProperty = DependencyProperty.Register(
nameof(IsSeekEnabled), typeof(bool), typeof(SeriesChart), new PropertyMetadata(true));
public static readonly DependencyProperty YMinimumProperty = DependencyProperty.Register(
nameof(YMinimum), typeof(double), typeof(SeriesChart), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty YMaximumProperty = DependencyProperty.Register(
nameof(YMaximum), typeof(double), typeof(SeriesChart), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty YPaddingProperty = DependencyProperty.Register(
nameof(YPadding), typeof(double), typeof(SeriesChart), new FrameworkPropertyMetadata(0.08, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty YLabelFormatterProperty = DependencyProperty.Register(
nameof(YLabelFormatter), typeof(Func), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty XLabelFormatterProperty = DependencyProperty.Register(
nameof(XLabelFormatter), typeof(Func), typeof(SeriesChart), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));
private const double LabelSize = 11;
private const double LegendHeight = 24;
private const double XAxisHeight = 18;
private int[] _decimated = [];
private Rect _plot;
private double _yLow;
private double _yHigh = 1;
private int _count;
private double _dataMin;
private double _dataMax;
private int _hover = -1;
private string? _hoverText;
private bool _dragging;
public SeriesChart()
: base(hasOverlay: true)
{
}
/// Lines to draw; replace the list (or use an observable collection) to update.
public IReadOnlyList? Series { get => (IReadOnlyList?)GetValue(SeriesProperty); set => SetValue(SeriesProperty, value); }
/// Frame markers drawn as dashed vertical lines in the marker colour.
public IReadOnlyList? Markers { get => (IReadOnlyList?)GetValue(MarkersProperty); set => SetValue(MarkersProperty, value); }
/// Explicit legend entries; null lists the titled series.
public IReadOnlyList? Legend { get => (IReadOnlyList?)GetValue(LegendProperty); set => SetValue(LegendProperty, value); }
/// Right-aligned text of the legend row (e.g. "flicker −67 % · max step 0.21 EV").
public string? Summary { get => (string?)GetValue(SummaryProperty); set => SetValue(SummaryProperty, value); }
public bool ShowLegend { get => (bool)GetValue(ShowLegendProperty); set => SetValue(ShowLegendProperty, value); }
public bool ShowYLabels { get => (bool)GetValue(ShowYLabelsProperty); set => SetValue(ShowYLabelsProperty, value); }
/// Playhead frame (two-way); −1 hides it.
public int CurrentIndex { get => (int)GetValue(CurrentIndexProperty); set => SetValue(CurrentIndexProperty, value); }
/// Whether clicking or dragging sets .
public bool IsSeekEnabled { get => (bool)GetValue(IsSeekEnabledProperty); set => SetValue(IsSeekEnabledProperty, value); }
/// Fixed bottom of the Y axis; NaN = automatic.
public double YMinimum { get => (double)GetValue(YMinimumProperty); set => SetValue(YMinimumProperty, value); }
/// Fixed top of the Y axis; NaN = automatic.
public double YMaximum { get => (double)GetValue(YMaximumProperty); set => SetValue(YMaximumProperty, value); }
/// Fraction of the data span added above and below an automatic range.
public double YPadding { get => (double)GetValue(YPaddingProperty); set => SetValue(YPaddingProperty, value); }
/// Culture-aware formatting of values (axis labels and readout).
public Func? YLabelFormatter { get => (Func?)GetValue(YLabelFormatterProperty); set => SetValue(YLabelFormatterProperty, value); }
/// Formatting of frame indices (readout header and, when set, X axis labels).
public Func? XLabelFormatter { get => (Func?)GetValue(XLabelFormatterProperty); set => SetValue(XLabelFormatterProperty, value); }
protected override Size MeasureOverride(Size availableSize) => new(0, 160);
protected override void OnDataChanged()
{
_count = 0;
_dataMin = double.PositiveInfinity;
_dataMax = double.NegativeInfinity;
if (Series is { } series)
{
for (var s = 0; s < series.Count; s++)
{
var values = series[s].Values.Span;
_count = Math.Max(_count, values.Length);
for (var i = 0; i < values.Length; i++)
{
var v = values[i];
if (!double.IsFinite(v)) continue;
if (v < _dataMin) _dataMin = v;
if (v > _dataMax) _dataMax = v;
}
}
}
_hover = -1;
_hoverText = null;
base.OnDataChanged();
}
protected override void OnRender(DrawingContext dc)
{
DrawHitArea(dc);
var size = RenderSize;
var scale = PixelScale;
var top = ShowLegend ? DrawLegendRow(dc, size.Width) : 0;
var bottom = size.Height - (XLabelFormatter is null ? 0 : XAxisHeight);
(_yLow, _yHigh) = YRange();
var ticks = NiceScale.Inner(_yLow, _yHigh, Math.Max(2, (int)((bottom - top) / 36)));
var format = YLabelFormatter ?? DefaultFormat;
var labels = new FormattedText?[ticks.Count];
var labelWidth = 0.0;
if (ShowYLabels)
{
var labelBrush = GetBrush("Brush.TextFaint");
for (var i = 0; i < ticks.Count; i++)
{
labels[i] = CreateText(format(ticks[i]), LabelSize, labelBrush);
labelWidth = Math.Max(labelWidth, labels[i]!.Width);
}
}
var left = labelWidth > 0 ? Math.Ceiling(labelWidth) + 8 : 0;
_plot = new Rect(left, top, Math.Max(0, size.Width - left), Math.Max(0, bottom - top));
if (_plot.Width < 1 || _plot.Height < 1)
{
RenderOverlay();
return;
}
var grid = GetHairline("Brush.Stroke");
for (var i = 0; i < ticks.Count; i++)
{
var y = PixelGrid.SnapLine(Y(ticks[i]), grid.Thickness, scale);
dc.DrawLine(grid, new Point(_plot.Left, y), new Point(_plot.Right, y));
if (labels[i] is { } label) dc.DrawText(label, new Point(left - 8 - label.Width, y - label.Height / 2));
}
if (XLabelFormatter is { } xFormat) DrawXLabels(dc, xFormat);
DrawMarkers(dc, scale);
dc.PushClip(new RectangleGeometry(_plot));
if (Series is { } series)
for (var s = 0; s < series.Count; s++) DrawSeries(dc, series[s], scale);
dc.Pop();
RenderOverlay();
}
protected override void OnRenderOverlay(DrawingContext dc)
{
if (_plot.Width < 1 || _count == 0) return;
var scale = PixelScale;
if (_hover >= 0)
{
var hair = GetHairline("Brush.TextFaint");
var x = PixelGrid.SnapLine(X(_hover), hair.Thickness, scale);
dc.DrawLine(hair, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
if (Series is { } series)
{
for (var s = 0; s < series.Count; s++)
{
var values = series[s].Values.Span;
if (_hover >= values.Length || !double.IsFinite(values[_hover])) continue;
dc.DrawEllipse(GetBrush(series[s].BrushKey), null, new Point(X(_hover), Y(values[_hover])), 3, 3);
}
}
}
if (CurrentIndex >= 0 && CurrentIndex < _count)
{
var pen = GetHairline("Brush.Accent");
var x = PixelGrid.SnapLine(X(CurrentIndex), pen.Thickness, scale);
dc.DrawLine(pen, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
}
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
var p = e.GetPosition(this);
if (!IsSeekEnabled || _count == 0 || !_plot.Contains(p)) return;
_dragging = CaptureMouse();
SetCurrentValue(CurrentIndexProperty, IndexAt(p.X));
e.Handled = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
var p = e.GetPosition(this);
if (_dragging) SetCurrentValue(CurrentIndexProperty, IndexAt(p.X));
if (_count == 0 || !_plot.Contains(p))
{
ClearHover();
return;
}
var index = IndexAt(p.X);
if (index != _hover)
{
_hover = index;
_hoverText = ReadoutText(index, p.X);
RenderOverlay();
}
Readout.Show(_hoverText, p);
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
if (_dragging) ReleaseMouseCapture();
}
protected override void OnLostMouseCapture(MouseEventArgs e)
{
base.OnLostMouseCapture(e);
_dragging = false;
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
ClearHover();
}
private static string DefaultFormat(double value) => value.ToString("G4", Loc.Culture);
private static void OnOverlayPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((SeriesChart)d).RenderOverlay();
private (double Low, double High) YRange()
{
var (low, high) = _dataMin <= _dataMax ? NiceScale.Pad(_dataMin, _dataMax, YPadding) : (0.0, 1.0);
if (double.IsFinite(YMinimum)) low = YMinimum;
if (double.IsFinite(YMaximum)) high = YMaximum;
return high > low ? (low, high) : NiceScale.Pad(low, low, 0);
}
private double X(double index) => _count <= 1 ? _plot.Left + _plot.Width / 2 : _plot.Left + index * _plot.Width / (_count - 1);
private double Y(double value) => _plot.Bottom - (value - _yLow) / (_yHigh - _yLow) * _plot.Height;
private int IndexAt(double x)
{
if (_count <= 1 || _plot.Width <= 0) return 0;
return (int)Math.Clamp(Math.Round((x - _plot.Left) / _plot.Width * (_count - 1)), 0, _count - 1);
}
/// Draws the legend row and returns the plot top.
private double DrawLegendRow(DrawingContext dc, double width)
{
var items = Legend ?? AutoLegend();
if (items.Count == 0 && string.IsNullOrEmpty(Summary)) return 0;
var right = width;
if (!string.IsNullOrEmpty(Summary))
{
var summary = CreateText(Summary, LabelSize, GetBrush("Brush.TextMuted"));
right -= summary.Width;
dc.DrawText(summary, new Point(right, 0));
right -= 16;
}
DrawLegend(dc, items, new Point(0, 0), right, LabelSize);
return LegendHeight;
}
private List AutoLegend()
{
var items = new List();
if (Series is not { } series) return items;
for (var s = 0; s < series.Count; s++)
{
var item = series[s];
if (!item.ShowInLegend || string.IsNullOrEmpty(item.Title)) continue;
var swatch = item.Dash switch
{
LineDash.Dashed => LegendSwatch.DashedLine,
LineDash.Dotted => LegendSwatch.DottedLine,
_ => LegendSwatch.Line,
};
items.Add(new ChartLegendItem(item.Title, item.BrushKey, swatch));
}
return items;
}
private void DrawXLabels(DrawingContext dc, Func format)
{
if (_count < 2) return;
var ticks = NiceScale.Inner(0, _count - 1, Math.Max(2, (int)(_plot.Width / 90)));
var brush = GetBrush("Brush.TextFaint");
var lastRight = double.NegativeInfinity;
for (var i = 0; i < ticks.Count; i++)
{
var v = ticks[i];
if (Math.Abs(v - Math.Round(v)) > 1e-9) continue;
var text = CreateText(format(v), LabelSize, brush);
var x = Math.Clamp(X(v) - text.Width / 2, 0, Math.Max(0, ActualWidth - text.Width));
if (x < lastRight + 8) continue;
dc.DrawText(text, new Point(x, _plot.Bottom + 4));
lastRight = x + text.Width;
}
}
private void DrawMarkers(DrawingContext dc, double scale)
{
if (Markers is not { Count: > 0 } markers) return;
var thickness = PixelGrid.SnapThickness(1, scale);
for (var i = 0; i < markers.Count; i++)
{
var m = markers[i];
if (m.Index < 0 || m.Index >= _count) continue;
var pen = GetPen(TimelineMarker.BrushKeyOf(m.Kind), thickness, LineDash.Dashed);
var x = PixelGrid.SnapLine(X(m.Index), thickness, scale);
dc.DrawLine(pen, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
}
}
private void DrawSeries(DrawingContext dc, ChartSeries series, double scale)
{
var values = series.Values.Span;
if (values.Length == 0) return;
var columns = Math.Max(1, (int)Math.Ceiling(_plot.Width * scale));
var capacity = MinMaxDecimator.Capacity(values.Length, columns);
if (_decimated.Length < capacity) _decimated = new int[capacity];
var n = MinMaxDecimator.Decimate(values, columns, _decimated);
var geometry = new StreamGeometry();
using (var ctx = geometry.Open())
{
var open = false;
for (var k = 0; k < n; k++)
{
var i = _decimated[k];
if (i == MinMaxDecimator.Gap)
{
open = false;
continue;
}
var p = new Point(X(i), Y(values[i]));
if (open)
{
ctx.LineTo(p, true, true);
}
else
{
ctx.BeginFigure(p, false, false);
open = true;
}
}
}
geometry.Freeze();
dc.DrawGeometry(null, GetPen(series.BrushKey, series.Thickness, series.Dash), geometry);
}
private string? ReadoutText(int index, double x)
{
var format = YLabelFormatter ?? DefaultFormat;
var text = new StringBuilder(XLabelFormatter?.Invoke(index) ?? index.ToString("N0", Loc.Culture));
if (Series is { } series)
{
for (var s = 0; s < series.Count; s++)
{
var values = series[s].Values.Span;
if (index >= values.Length || !double.IsFinite(values[index])) continue;
text.AppendLine();
if (!string.IsNullOrEmpty(series[s].Title)) text.Append(series[s].Title).Append(": ");
text.Append(format(values[index]));
}
}
if (Markers is { } markers)
{
for (var i = 0; i < markers.Count; i++)
{
var m = markers[i];
if (string.IsNullOrEmpty(m.Label) || m.Index < 0 || m.Index >= _count || Math.Abs(X(m.Index) - x) > 4) continue;
text.AppendLine().Append(m.Label);
}
}
return text.ToString();
}
private void ClearHover()
{
Readout.Hide();
if (_hover < 0) return;
_hover = -1;
_hoverText = null;
RenderOverlay();
}
}