using System;
using UnityEngine;
namespace NEG.Utils.Timing
{
public class TimeMachine
{
private double timeInternal;
public TimeMachine()
{
timeInternal = 0;
}
///
/// Adds time into the TimeMachine
///
/// Amount of time to be added
public void Accumulate(double time) => timeInternal += time;
///
/// Retrieves given amount of time from the TimeMachine
///
///
/// Amount of time retrieved
public double Retrieve(double maxTime)
{
if(!double.IsFinite(maxTime))
{
double timeRetrieved = timeInternal;
timeInternal = 0;
return timeRetrieved;
}
double timeLeft = timeInternal - maxTime;
timeInternal = Math.Max(timeLeft, 0);
return Math.Min(maxTime + timeLeft, maxTime);
}
///
/// Attempts to retrieves given amount of time from the TimeMachine
/// If there is enough accumulated in this machine subtracts that amount and returns true, otherwise returns false
///
///
public bool TryRetrieve(double time)
{
if (!(timeInternal >= time))
return false;
timeInternal -= time;
return true;
}
///
/// Result is equivalent to calling as many times as possible, but is faster for larger values
///
/// Single unit of warp time, must be positive
/// Maximum amount of warps, must be positive
/// Amount of warps
public int RetrieveAll(double interval, int limit = int.MaxValue)
{
int result = Mathf.FloorToInt((float)(timeInternal / interval));
result = Math.Clamp(result, 0, limit);
timeInternal -= result * interval;
return result;
}
}
}