feat(ui-visuals): add CurveEditor for time remap and keyframes
Edits control points in place (add, drag with monotone X, delete, nudge) and draws the curve from a supplied evaluator, with grid, diagonal and playhead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
1 file changed
+379
@@ -0,0 +1,379 @@
|
||||
using System.Collections.Specialized;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using Titano.Core.Localization;
|
||||
|
||||
namespace Titano.Ui.Visuals;
|
||||
|
||||
/// <summary>Editing rules of a <see cref="CurveEditor"/>.</summary>
|
||||
public enum CurveEditMode
|
||||
{
|
||||
/// <summary>Keyframes ordered by time (virtual camera): X stays increasing, the ends may move.</summary>
|
||||
Keyframes,
|
||||
|
||||
/// <summary>Time remap: X stays increasing and the end points are pinned to X = 0 and X = 1.</summary>
|
||||
TimeRemap,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spline/keyframe editor in normalised [0, 1]² space (BRIEF §12.3: Time remap curve, Camera keyframes).
|
||||
/// Control points come from <see cref="Points"/> and are edited in place (double-click adds, drag moves with the
|
||||
/// X order constrained by <see cref="CurveMath"/>, Delete removes, arrows nudge); the curve itself is drawn by
|
||||
/// sampling <see cref="Evaluator"/> once per device-pixel column, so the engine's Fritsch–Carlson spline is what
|
||||
/// the user sees. Grid, optional identity diagonal and a playhead are drawn; hovering or dragging a point reads
|
||||
/// out its coordinates. <see cref="EditCompletedEvent"/> fires after each add, delete, nudge or finished drag.
|
||||
/// </summary>
|
||||
public sealed class CurveEditor : DrawingElement
|
||||
{
|
||||
public static readonly DependencyProperty PointsProperty = DependencyProperty.Register(
|
||||
nameof(Points), typeof(IList<Point>), typeof(CurveEditor), new PropertyMetadata(null, OnDataPropertyChanged));
|
||||
|
||||
public static readonly DependencyProperty EvaluatorProperty = DependencyProperty.Register(
|
||||
nameof(Evaluator), typeof(Func<double, double>), typeof(CurveEditor), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty ModeProperty = DependencyProperty.Register(
|
||||
nameof(Mode), typeof(CurveEditMode), typeof(CurveEditor), new PropertyMetadata(CurveEditMode.Keyframes));
|
||||
|
||||
public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register(
|
||||
nameof(SelectedIndex), typeof(int), typeof(CurveEditor),
|
||||
new FrameworkPropertyMetadata(-1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsRender, null, CoerceSelectedIndex));
|
||||
|
||||
public static readonly DependencyProperty PlayheadPositionProperty = DependencyProperty.Register(
|
||||
nameof(PlayheadPosition), typeof(double), typeof(CurveEditor), new PropertyMetadata(double.NaN, (d, _) => ((CurveEditor)d).RenderOverlay()));
|
||||
|
||||
public static readonly DependencyProperty ShowDiagonalProperty = DependencyProperty.Register(
|
||||
nameof(ShowDiagonal), typeof(bool), typeof(CurveEditor), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
|
||||
public static readonly DependencyProperty MinimumGapProperty = DependencyProperty.Register(
|
||||
nameof(MinimumGap), typeof(double), typeof(CurveEditor), new PropertyMetadata(CurveMath.DefaultMinGap));
|
||||
|
||||
public static readonly DependencyProperty XLabelFormatterProperty = DependencyProperty.Register(
|
||||
nameof(XLabelFormatter), typeof(Func<double, string>), typeof(CurveEditor), new PropertyMetadata(null));
|
||||
|
||||
public static readonly DependencyProperty YLabelFormatterProperty = DependencyProperty.Register(
|
||||
nameof(YLabelFormatter), typeof(Func<double, string>), typeof(CurveEditor), new PropertyMetadata(null));
|
||||
|
||||
public static readonly RoutedEvent EditCompletedEvent = EventManager.RegisterRoutedEvent(
|
||||
nameof(EditCompleted), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CurveEditor));
|
||||
|
||||
private const double Inset = 7;
|
||||
private const double PointRadius = 4.5;
|
||||
private const double HitRadius = 8;
|
||||
|
||||
private double[] _xs = [];
|
||||
private double[] _ys = [];
|
||||
private double[] _viewX = [];
|
||||
private double[] _viewY = [];
|
||||
private int _count;
|
||||
private Rect _plot;
|
||||
private int _hover = -1;
|
||||
private bool _dragging;
|
||||
private bool _moved;
|
||||
|
||||
static CurveEditor()
|
||||
{
|
||||
FocusableProperty.OverrideMetadata(typeof(CurveEditor), new FrameworkPropertyMetadata(true));
|
||||
}
|
||||
|
||||
public CurveEditor()
|
||||
: base(hasOverlay: true)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Control points in [0, 1]², ordered by X; edited in place unless the list is read-only.</summary>
|
||||
public IList<Point>? Points { get => (IList<Point>?)GetValue(PointsProperty); set => SetValue(PointsProperty, value); }
|
||||
|
||||
/// <summary>The curve through the points (x → y in [0, 1]); null draws straight segments.</summary>
|
||||
public Func<double, double>? Evaluator { get => (Func<double, double>?)GetValue(EvaluatorProperty); set => SetValue(EvaluatorProperty, value); }
|
||||
|
||||
public CurveEditMode Mode { get => (CurveEditMode)GetValue(ModeProperty); set => SetValue(ModeProperty, value); }
|
||||
|
||||
/// <summary>Selected point (two-way); −1 = none.</summary>
|
||||
public int SelectedIndex { get => (int)GetValue(SelectedIndexProperty); set => SetValue(SelectedIndexProperty, value); }
|
||||
|
||||
/// <summary>Playhead X in [0, 1]; NaN hides it.</summary>
|
||||
public double PlayheadPosition { get => (double)GetValue(PlayheadPositionProperty); set => SetValue(PlayheadPositionProperty, value); }
|
||||
|
||||
/// <summary>Dashed identity line (y = x), the "no remap" reference.</summary>
|
||||
public bool ShowDiagonal { get => (bool)GetValue(ShowDiagonalProperty); set => SetValue(ShowDiagonalProperty, value); }
|
||||
|
||||
/// <summary>Minimum X distance between neighbouring points.</summary>
|
||||
public double MinimumGap { get => (double)GetValue(MinimumGapProperty); set => SetValue(MinimumGapProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware formatting of X in readouts (e.g. output time).</summary>
|
||||
public Func<double, string>? XLabelFormatter { get => (Func<double, string>?)GetValue(XLabelFormatterProperty); set => SetValue(XLabelFormatterProperty, value); }
|
||||
|
||||
/// <summary>Culture-aware formatting of Y in readouts (e.g. source time).</summary>
|
||||
public Func<double, string>? YLabelFormatter { get => (Func<double, string>?)GetValue(YLabelFormatterProperty); set => SetValue(YLabelFormatterProperty, value); }
|
||||
|
||||
public event RoutedEventHandler EditCompleted
|
||||
{
|
||||
add => AddHandler(EditCompletedEvent, value);
|
||||
remove => RemoveHandler(EditCompletedEvent, value);
|
||||
}
|
||||
|
||||
private bool PinEnds => Mode == CurveEditMode.TimeRemap;
|
||||
|
||||
private bool IsEditable => Points is { IsReadOnly: false };
|
||||
|
||||
protected override Size MeasureOverride(Size availableSize) => new(0, 160);
|
||||
|
||||
protected override void OnDataChanged()
|
||||
{
|
||||
var points = Points;
|
||||
_count = points?.Count ?? 0;
|
||||
if (_xs.Length < _count)
|
||||
{
|
||||
_xs = new double[_count];
|
||||
_ys = new double[_count];
|
||||
_viewX = new double[_count];
|
||||
_viewY = new double[_count];
|
||||
}
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
_xs[i] = points![i].X;
|
||||
_ys[i] = points[i].Y;
|
||||
}
|
||||
_hover = -1;
|
||||
CoerceValue(SelectedIndexProperty);
|
||||
base.OnDataChanged();
|
||||
}
|
||||
|
||||
protected override void OnRender(DrawingContext dc)
|
||||
{
|
||||
DrawHitArea(dc);
|
||||
_plot = new Rect(Inset, Inset, Math.Max(0, ActualWidth - 2 * Inset), Math.Max(0, ActualHeight - 2 * Inset));
|
||||
if (_plot.Width < 1 || _plot.Height < 1) return;
|
||||
var scale = PixelScale;
|
||||
var grid = GetHairline("Brush.Stroke");
|
||||
for (var i = 0; i <= 4; i++)
|
||||
{
|
||||
var x = PixelGrid.SnapLine(X(i / 4.0), grid.Thickness, scale);
|
||||
var y = PixelGrid.SnapLine(Y(i / 4.0), grid.Thickness, scale);
|
||||
dc.DrawLine(grid, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
|
||||
dc.DrawLine(grid, new Point(_plot.Left, y), new Point(_plot.Right, y));
|
||||
}
|
||||
if (ShowDiagonal) dc.DrawLine(GetPen("Brush.TextFaint", 1, LineDash.Dashed), new Point(X(0), Y(0)), new Point(X(1), Y(1)));
|
||||
|
||||
dc.PushClip(new RectangleGeometry(new Rect(0, 0, ActualWidth, ActualHeight)));
|
||||
DrawCurve(dc, scale);
|
||||
dc.Pop();
|
||||
|
||||
var fill = GetBrush("Brush.Surface");
|
||||
var accent = GetBrush("Brush.Accent");
|
||||
var stroke = GetPen("Brush.Accent", 1.5);
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
var selected = i == SelectedIndex;
|
||||
var radius = i == _hover || selected ? PointRadius + 1 : PointRadius;
|
||||
dc.DrawEllipse(selected ? accent : fill, stroke, new Point(X(_xs[i]), Y(_ys[i])), radius, radius);
|
||||
}
|
||||
RenderOverlay();
|
||||
}
|
||||
|
||||
protected override void OnRenderOverlay(DrawingContext dc)
|
||||
{
|
||||
var position = PlayheadPosition;
|
||||
if (!double.IsFinite(position) || _plot.Width < 1) return;
|
||||
var pen = GetHairline("Brush.Accent");
|
||||
var x = PixelGrid.SnapLine(X(Math.Clamp(position, 0, 1)), pen.Thickness, PixelScale);
|
||||
dc.DrawLine(pen, new Point(x, _plot.Top), new Point(x, _plot.Bottom));
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonDown(e);
|
||||
Focus();
|
||||
var p = e.GetPosition(this);
|
||||
var hit = HitTest(p);
|
||||
if (hit >= 0)
|
||||
{
|
||||
SetCurrentValue(SelectedIndexProperty, hit);
|
||||
_moved = false;
|
||||
_dragging = IsEditable && CaptureMouse();
|
||||
}
|
||||
else if (e.ClickCount == 2)
|
||||
{
|
||||
Add(p);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetCurrentValue(SelectedIndexProperty, -1);
|
||||
}
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseMove(e);
|
||||
var p = e.GetPosition(this);
|
||||
if (_dragging && SelectedIndex >= 0)
|
||||
{
|
||||
_moved |= Move(SelectedIndex, ToX(p.X), ToY(p.Y));
|
||||
Readout.Show(ReadoutText(SelectedIndex), p);
|
||||
return;
|
||||
}
|
||||
var hover = HitTest(p);
|
||||
if (hover != _hover)
|
||||
{
|
||||
_hover = hover;
|
||||
InvalidateVisual();
|
||||
}
|
||||
Readout.Show(hover >= 0 ? ReadoutText(hover) : null, p);
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonUp(e);
|
||||
if (_dragging) ReleaseMouseCapture();
|
||||
}
|
||||
|
||||
protected override void OnLostMouseCapture(MouseEventArgs e)
|
||||
{
|
||||
base.OnLostMouseCapture(e);
|
||||
if (!_dragging) return;
|
||||
_dragging = false;
|
||||
if (_moved) RaiseEvent(new RoutedEventArgs(EditCompletedEvent));
|
||||
_moved = false;
|
||||
}
|
||||
|
||||
protected override void OnMouseLeave(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseLeave(e);
|
||||
if (_dragging) return;
|
||||
Readout.Hide();
|
||||
if (_hover < 0) return;
|
||||
_hover = -1;
|
||||
InvalidateVisual();
|
||||
}
|
||||
|
||||
protected override void OnQueryCursor(QueryCursorEventArgs e)
|
||||
{
|
||||
base.OnQueryCursor(e);
|
||||
if (e.Handled || (!_dragging && _hover < 0)) return;
|
||||
e.Cursor = _dragging ? Cursors.SizeAll : Cursors.Hand;
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
var index = SelectedIndex;
|
||||
if (e.Handled || index < 0 || index >= _count || !IsEditable) return;
|
||||
var step = (Keyboard.Modifiers & ModifierKeys.Shift) != 0 ? 0.1 : 0.01;
|
||||
var changed = e.Key switch
|
||||
{
|
||||
Key.Delete or Key.Back => Remove(index),
|
||||
Key.Left => Move(index, _xs[index] - step, _ys[index]),
|
||||
Key.Right => Move(index, _xs[index] + step, _ys[index]),
|
||||
Key.Up => Move(index, _xs[index], _ys[index] + step),
|
||||
Key.Down => Move(index, _xs[index], _ys[index] - step),
|
||||
_ => (bool?)null,
|
||||
};
|
||||
if (changed is null) return;
|
||||
e.Handled = true;
|
||||
if (changed.Value) RaiseEvent(new RoutedEventArgs(EditCompletedEvent));
|
||||
}
|
||||
|
||||
private static object CoerceSelectedIndex(DependencyObject d, object value)
|
||||
{
|
||||
var index = (int)value;
|
||||
return index >= 0 && index < ((CurveEditor)d)._count ? index : -1;
|
||||
}
|
||||
|
||||
private double X(double x) => _plot.Left + x * _plot.Width;
|
||||
|
||||
private double Y(double y) => _plot.Bottom - y * _plot.Height;
|
||||
|
||||
private double ToX(double x) => _plot.Width > 0 ? (x - _plot.Left) / _plot.Width : 0;
|
||||
|
||||
private double ToY(double y) => _plot.Height > 0 ? (_plot.Bottom - y) / _plot.Height : 0;
|
||||
|
||||
private void DrawCurve(DrawingContext dc, double scale)
|
||||
{
|
||||
var evaluator = Evaluator;
|
||||
if (evaluator is null && _count < 2) return;
|
||||
var geometry = new StreamGeometry();
|
||||
using (var ctx = geometry.Open())
|
||||
{
|
||||
if (evaluator is not null)
|
||||
{
|
||||
var columns = Math.Max(2, (int)Math.Ceiling(_plot.Width * scale) + 1);
|
||||
for (var c = 0; c < columns; c++)
|
||||
{
|
||||
var x = c / (double)(columns - 1);
|
||||
var p = new Point(X(x), Y(evaluator(x)));
|
||||
if (c == 0) ctx.BeginFigure(p, false, false);
|
||||
else ctx.LineTo(p, true, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ctx.BeginFigure(new Point(X(_xs[0]), Y(_ys[0])), false, false);
|
||||
for (var i = 1; i < _count; i++) ctx.LineTo(new Point(X(_xs[i]), Y(_ys[i])), true, true);
|
||||
}
|
||||
}
|
||||
geometry.Freeze();
|
||||
dc.DrawGeometry(null, GetPen("Brush.Accent", 2), geometry);
|
||||
}
|
||||
|
||||
private int HitTest(Point p)
|
||||
{
|
||||
if (_count == 0 || _plot.Width < 1) return -1;
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
_viewX[i] = X(_xs[i]);
|
||||
_viewY[i] = Y(_ys[i]);
|
||||
}
|
||||
return CurveMath.HitTest(_viewX.AsSpan(0, _count), _viewY.AsSpan(0, _count), p.X, p.Y, HitRadius);
|
||||
}
|
||||
|
||||
/// <summary>Moves point <paramref name="index"/> towards (x, y) within the constraints; true when it changed.</summary>
|
||||
private bool Move(int index, double x, double y)
|
||||
{
|
||||
if (Points is not { IsReadOnly: false } points) return false;
|
||||
var cx = CurveMath.ConstrainX(_xs.AsSpan(0, _count), index, x, MinimumGap, PinEnds);
|
||||
var cy = CurveMath.ConstrainY(y);
|
||||
if (cx == _xs[index] && cy == _ys[index]) return false;
|
||||
points[index] = new Point(cx, cy);
|
||||
AfterEdit(points);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Add(Point at)
|
||||
{
|
||||
if (Points is not { IsReadOnly: false } points) return;
|
||||
var x = ToX(at.X);
|
||||
var index = CurveMath.InsertionIndex(_xs.AsSpan(0, _count), x, MinimumGap, PinEnds);
|
||||
if (index < 0) return;
|
||||
points.Insert(index, new Point(x, CurveMath.ConstrainY(ToY(at.Y))));
|
||||
AfterEdit(points);
|
||||
SetCurrentValue(SelectedIndexProperty, index);
|
||||
RaiseEvent(new RoutedEventArgs(EditCompletedEvent));
|
||||
}
|
||||
|
||||
private bool Remove(int index)
|
||||
{
|
||||
if (Points is not { IsReadOnly: false } points || !CurveMath.CanRemove(_count, index, PinEnds)) return false;
|
||||
points.RemoveAt(index);
|
||||
AfterEdit(points);
|
||||
SetCurrentValue(SelectedIndexProperty, Math.Min(index, _count - 1));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Observable lists notify through the collection watcher; plain lists are re-read here.</summary>
|
||||
private void AfterEdit(IList<Point> points)
|
||||
{
|
||||
if (points is not INotifyCollectionChanged) OnDataChanged();
|
||||
}
|
||||
|
||||
private string ReadoutText(int index)
|
||||
{
|
||||
var x = XLabelFormatter ?? DefaultFormat;
|
||||
var y = YLabelFormatter ?? DefaultFormat;
|
||||
return x(_xs[index]) + " → " + y(_ys[index]);
|
||||
}
|
||||
|
||||
private static string DefaultFormat(double value) => value.ToString("0.###", Loc.Culture);
|
||||
}
|
||||
Reference in new issue
Block a user