Client LuaCsForBarotrauma
LuaCsTimer.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Diagnostics;
4 
5 namespace Barotrauma
6 {
7  public class LuaCsTimer
8  {
9  public static double Time => Timing.TotalTime;
10  public static double GetTime() => Time;
11  public static double AccumulatorMax
12  {
13  get
14  {
15  return Timing.AccumulatorMax;
16  }
17  set
18  {
19  Timing.AccumulatorMax = value;
20  }
21  }
22 
23  private class TimerComparer : IComparer<TimedAction>
24  {
25  public int Compare(TimedAction timedAction1, TimedAction timedAction2)
26  {
27  if (timedAction1 == null || timedAction2 == null)
28  return 0;
29  return -Math.Sign(timedAction2.ExecutionTime - timedAction1.ExecutionTime);
30  }
31  }
32 
33  private class TimedAction
34  {
35  public LuaCsAction Action
36  {
37  get;
38  private set;
39  }
40 
41  public double ExecutionTime
42  {
43  get;
44  private set;
45  }
46 
47  public TimedAction(LuaCsAction action, int delayMs)
48  {
49  this.Action = action;
50  ExecutionTime = Time + (delayMs / 1000f);
51  }
52  }
53 
54  private List<TimedAction> timedActions = new List<TimedAction>();
55 
56  private void AddTimer(TimedAction timedAction)
57  {
58  if (timedAction == null)
59  {
60  throw new ArgumentNullException(nameof(timedAction));
61  }
62 
63  lock (timedActions)
64  {
65  int insertionPoint = timedActions.BinarySearch(timedAction, new TimerComparer());
66 
67  if (insertionPoint < 0)
68  {
69  insertionPoint = ~insertionPoint;
70  }
71 
72  timedActions.Insert(insertionPoint, timedAction);
73  }
74  }
75 
76  public void Update()
77  {
78  lock (timedActions)
79  {
80  TimedAction[] timedCopy = timedActions.ToArray();
81  for (int i = 0; i < timedCopy.Length; i++)
82  {
83  TimedAction timedAction = timedCopy[i];
84  if (Time >= timedAction.ExecutionTime)
85  {
86  try
87  {
88  timedAction.Action();
89  }
90  catch (Exception e)
91  {
92  LuaCsLogger.HandleException(e, LuaCsMessageOrigin.CSharpMod);
93  }
94 
95  timedActions.Remove(timedAction);
96  }
97  else
98  {
99  break;
100  }
101  }
102  }
103  }
104 
105  public void Clear()
106  {
107  timedActions = new List<TimedAction>();
108  }
109 
110  public void Wait(LuaCsAction action, int millisecondDelay)
111  {
112  TimedAction timedAction = new TimedAction(action, millisecondDelay);
113  AddTimer(timedAction);
114  }
115 
116  public void NextFrame(LuaCsAction action)
117  {
118  TimedAction timedAction = new TimedAction(action, 0);
119  AddTimer(timedAction);
120  }
121  }
122 }
static void HandleException(Exception ex, LuaCsMessageOrigin origin)
static double GetTime()
static double AccumulatorMax
Definition: LuaCsTimer.cs:12
void NextFrame(LuaCsAction action)
Definition: LuaCsTimer.cs:116
void Wait(LuaCsAction action, int millisecondDelay)
Definition: LuaCsTimer.cs:110
static double Time
Definition: LuaCsTimer.cs:9
delegate void LuaCsAction(params object[] args)