using System;
using System.Collections.Generic;
using System.Diagnostics;
using OpenNest.CNC;
namespace OpenNest.Desktop.Interaction;
///
/// The Cut Simulator's playhead over a , without drawing: the time,
/// play and pause at a speed, the jumps between parts, cutouts and moves, and which parts the
/// torch has not reached. The host runs a timer that calls while
/// and redraws after each change.
///
public sealed class CutSimulationPlayback
{
/// The simulator's speed choices, as multiples of real time.
public static IReadOnlyList Speeds { get; } = new double[] { 1, 2, 5, 10, 25, 50, 100, 250 };
/// The speed the simulator starts at.
public const double DefaultSpeed = 5;
/// The index of in .
public static int DefaultSpeedIndex => 2;
private readonly Stopwatch clock = new();
private CutSimulation simulation;
private TimeSpan time;
private bool playing;
/// Raised when the playhead, play state or timeline changes.
public event EventHandler Changed;
public CutSimulation Simulation => simulation;
public bool IsActive => simulation != null;
public bool IsPlaying => playing;
/// Simulated time per wall-clock time.
public double Speed { get; set; } = 10;
/// The playhead, kept within the timeline; nothing changes without one.
public TimeSpan Time
{
get => time;
set
{
if (simulation == null)
return;
time = value < TimeSpan.Zero ? TimeSpan.Zero : value > simulation.TotalTime ? simulation.TotalTime : value;
Changed?.Invoke(this, EventArgs.Empty);
}
}
///
/// Shows , keeping the torch where it was when the moves are the same
/// (new rates or acceleration only retime them), else keeping the playhead's time.
///
public void Load(CutSimulation value)
{
var anchored = Anchor(simulation, value, time);
simulation = value;
Time = anchored;
if (simulation == null)
Pause();
Changed?.Invoke(this, EventArgs.Empty);
}
/// Where on falls on .
public static TimeSpan Anchor(CutSimulation old, CutSimulation next, TimeSpan time)
{
if (old == null || next == null || old.Steps.Count == 0 || old.Steps.Count != next.Steps.Count)
return time;
var index = old.IndexAt(time);
if (index >= old.Steps.Count)
return next.TotalTime;
return next.TimeAt(index, old.FractionAt(index, time));
}
/// Plays from the playhead, or from the start once it is at the end.
public void Play()
{
if (simulation == null || simulation.Steps.Count == 0)
return;
if (time >= simulation.TotalTime)
Time = TimeSpan.Zero;
clock.Restart();
playing = true;
Changed?.Invoke(this, EventArgs.Empty);
}
public void Pause()
{
if (!playing)
return;
playing = false;
clock.Reset();
Changed?.Invoke(this, EventArgs.Empty);
}
/// Drops the timeline and stops.
public void Clear()
{
playing = false;
clock.Reset();
simulation = null;
time = TimeSpan.Zero;
Changed?.Invoke(this, EventArgs.Empty);
}
/// Moves the playhead by the wall time since the last advance (or since Play).
public void Advance()
{
var elapsed = clock.Elapsed;
clock.Restart();
Advance(elapsed);
}
///
/// Moves the playhead by times , pausing at
/// the end.
///
public void Advance(TimeSpan wallElapsed)
{
if (simulation == null)
return;
var next = time + TimeSpan.FromTicks((long)(wallElapsed.Ticks * Speed));
time = next > simulation.TotalTime ? simulation.TotalTime : next;
Changed?.Invoke(this, EventArgs.Empty);
if (time >= simulation.TotalTime)
Pause();
}
///
/// The play button: pauses while playing; otherwise plays, first calling
/// (parts may have moved, which raises no plate event) when there
/// is no timeline or the playhead is at its start or end.
///
public void TogglePlay(Action rebuild)
{
if (playing)
{
Pause();
return;
}
if (simulation == null || time <= TimeSpan.Zero || time >= simulation.TotalTime)
rebuild?.Invoke();
Play();
}
/// Back to the start (Home), still playing if it was.
public void Restart() => Time = TimeSpan.Zero;
/// Pauses at the end.
public void End()
{
Pause();
Time = simulation?.TotalTime ?? TimeSpan.Zero;
}
public void NextContour() => Jump(sim => sim.NextContour(time));
public void PreviousContour() => Jump(sim => sim.PreviousContour(time));
public void NextPart() => Jump(sim => sim.NextPart(time));
public void PreviousPart() => Jump(sim => sim.PreviousPart(time));
// Jumps pause so the jumped-to contour stays on screen.
private void Jump(Func target)
{
if (simulation is not { } sim || sim.Steps.Count == 0)
return;
Pause();
Time = target(sim);
}
///
/// Pauses at the start of the next move ( > 0), or back at the
/// start of the current move, or of the one before when already there.
///
public void StepMove(int direction)
{
var sim = simulation;
if (sim == null || sim.Steps.Count == 0)
return;
Pause();
var index = System.Math.Clamp(sim.IndexAt(time), 0, sim.Steps.Count);
var atStart = index < sim.Steps.Count && time == sim.Steps[index].StartTime;
var target = direction > 0 ? index + 1 : atStart ? index - 1 : index;
Time = target <= 0 ? TimeSpan.Zero
: target >= sim.Steps.Count ? sim.TotalTime
: sim.Steps[target].StartTime;
}
/// The playhead as a fraction of the timeline (0 without one).
public double Progress =>
simulation is { } sim && sim.TotalTime > TimeSpan.Zero ? time / sim.TotalTime : 0;
/// Moves the playhead to of the timeline (a scrub).
public void Seek(double fraction)
{
if (simulation != null)
Time = simulation.TotalTime * fraction;
}
/// True for a part the torch has not started yet.
public bool IsPartPending(int partIndex)
{
if (simulation == null)
return false;
var index = simulation.IndexAt(time);
if (index >= simulation.Steps.Count)
return false;
if (index < 0)
return true;
var current = simulation.Steps[index];
// Travel toward a part has not touched it yet.
return partIndex > current.PartIndex
|| partIndex == current.PartIndex && current.Kind == CutSimulationStepKind.Rapid && !PartStarted(index);
}
private bool PartStarted(int index)
{
var part = simulation.Steps[index].PartIndex;
for (var i = index - 1; i >= 0 && simulation.Steps[i].PartIndex == part; i--)
{
if (simulation.Steps[i].Kind != CutSimulationStepKind.Rapid)
return true;
}
return false;
}
}