AnimancerEvent.Dispatcher.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using UnityEngine;
  6. namespace Animancer
  7. {
  8. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerEvent
  9. partial struct AnimancerEvent
  10. {
  11. /// <summary>
  12. /// A system which triggers events in an <see cref="Sequence"/>
  13. /// based on a target <see cref="State"/>.
  14. /// </summary>
  15. /// https://kybernetik.com.au/animancer/api/Animancer/Dispatcher
  16. public class Dispatcher : IHasDescription
  17. {
  18. /************************************************************************************************************************/
  19. /// <summary>The target state.</summary>
  20. public readonly AnimancerState State;
  21. /// <summary>
  22. /// <see cref="AnimancerState.OwnedEvents"/> and
  23. /// <see cref="AnimancerState.SharedEvents"/>.
  24. /// </summary>
  25. /// <remarks>Should never be null.</remarks>
  26. public Sequence Events { get; private set; }
  27. /// <summary><see cref="AnimancerState.HasOwnedEvents"/></summary>
  28. public bool HasOwnEvents { get; private set; }
  29. private float _PreviousNormalizedTime;
  30. private int _NextEventIndex = RecalculateEventIndex;
  31. private int _SequenceVersion = -1;// When version changes, next event index is invalid.
  32. private bool _WasPlayingForwards;// When direction changes, next event index is invalid.
  33. /// <summary>
  34. /// A special value for the <see cref="_NextEventIndex"/>
  35. /// which indicates that it needs to be recalculated.
  36. /// </summary>
  37. private const int RecalculateEventIndex = int.MinValue;
  38. /************************************************************************************************************************/
  39. /// <summary>Creates a new <see cref="Dispatcher"/>.</summary>
  40. public Dispatcher(AnimancerState state)
  41. {
  42. State = state;
  43. _PreviousNormalizedTime = state.NormalizedTime;
  44. #if UNITY_ASSERTIONS
  45. OptionalWarning.UnsupportedEvents.Log(state.UnsupportedEventsMessage, state.Graph?.Component);
  46. #endif
  47. }
  48. /************************************************************************************************************************/
  49. /// <summary>
  50. /// Setters for <see cref="AnimancerState.OwnedEvents"/>
  51. /// and <see cref="AnimancerState.SharedEvents"/>.
  52. /// </summary>
  53. public void SetEvents(Sequence events, bool isOwned)
  54. {
  55. Events = events;
  56. _NextEventIndex = RecalculateEventIndex;
  57. HasOwnEvents = isOwned;
  58. }
  59. /************************************************************************************************************************/
  60. /// <summary>Sets <see cref="HasOwnEvents"/> to <c>false</c>.</summary>
  61. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  62. public void DismissEventOwnership()
  63. => HasOwnEvents = false;
  64. /************************************************************************************************************************/
  65. /// <summary><see cref="AnimancerState.Events(object, out Sequence)"/>.</summary>
  66. public bool InitializeEvents(out Sequence events)
  67. {
  68. if (HasOwnEvents)
  69. {
  70. events = Events;
  71. return false;
  72. }
  73. Events = events = new(Events);
  74. _NextEventIndex = RecalculateEventIndex;
  75. _SequenceVersion = Events.Version;
  76. HasOwnEvents = true;
  77. return true;
  78. }
  79. /************************************************************************************************************************/
  80. /// <summary>[Internal]
  81. /// Notifies this dispatcher that the target's <see cref="Time"/> has changed.
  82. /// </summary>
  83. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  84. internal void OnSetTime()
  85. {
  86. // The Playable's time won't move in the same frame it was set,
  87. // so we'll just let the next frame grab its time.
  88. _PreviousNormalizedTime = float.NaN;
  89. }
  90. /************************************************************************************************************************/
  91. /// <inheritdoc/>
  92. public void UpdateEvents(bool raiseEvents)
  93. {
  94. State.GetEventDispatchInfo(out var length, out var normalizedTime, out var isLooping);
  95. // If we aren't raising events or don't have a previous time, just keep track of the time.
  96. if (!raiseEvents || float.IsNaN(_PreviousNormalizedTime))
  97. {
  98. _PreviousNormalizedTime = normalizedTime;
  99. // Since we aren't paying attention to the events,
  100. // we also aren't paying attention to which index the time corresponds to.
  101. _NextEventIndex = RecalculateEventIndex;
  102. return;
  103. }
  104. // If the sequence is modified, we need to recalculate the next event index.
  105. var sequenceVersion = Events.Version;
  106. if (_SequenceVersion != sequenceVersion)
  107. {
  108. _SequenceVersion = sequenceVersion;
  109. _NextEventIndex = RecalculateEventIndex;
  110. }
  111. if (length > 0)
  112. {
  113. if (_PreviousNormalizedTime == normalizedTime)
  114. return;
  115. CheckGeneralEvents(normalizedTime, isLooping);
  116. CheckEndEvent(normalizedTime);
  117. _PreviousNormalizedTime = normalizedTime;
  118. }
  119. else// Length zero, negative, or NaN.
  120. {
  121. UpdateZeroLength();
  122. }
  123. }
  124. /************************************************************************************************************************/
  125. /// <summary>If the state has zero length, trigger its events every frame.</summary>
  126. private void UpdateZeroLength()
  127. {
  128. var speed = State.EffectiveSpeed;
  129. if (speed == 0)
  130. return;
  131. if (Events.Count > 0)
  132. {
  133. int playDirectionInt;
  134. if (speed < 0)
  135. {
  136. playDirectionInt = -1;
  137. if (_NextEventIndex == RecalculateEventIndex ||
  138. _WasPlayingForwards)
  139. {
  140. _NextEventIndex = Events.Count - 1;
  141. _WasPlayingForwards = false;
  142. }
  143. }
  144. else
  145. {
  146. playDirectionInt = 1;
  147. if (_NextEventIndex == RecalculateEventIndex ||
  148. !_WasPlayingForwards)
  149. {
  150. _NextEventIndex = 0;
  151. _WasPlayingForwards = true;
  152. }
  153. }
  154. if (!InvokeAllEvents(Events, 1, playDirectionInt))
  155. return;
  156. }
  157. var endEvent = Events.EndEvent;
  158. if (endEvent.callback != null)
  159. endEvent.DelayInvoke(EndEventName, State);
  160. }
  161. /************************************************************************************************************************/
  162. /// <summary>General events are triggered on the frame when their time passes.</summary>
  163. /// <remarks>Looping animations trigger their events every loop.</remarks>
  164. private void CheckGeneralEvents(float currentTime, bool isLooping)
  165. {
  166. var count = Events.Count;
  167. if (count == 0)
  168. {
  169. _NextEventIndex = 0;
  170. return;
  171. }
  172. ValidateNextEventIndex(
  173. isLooping,
  174. ref currentTime,
  175. out var playDirectionFloat,
  176. out var playDirectionInt);
  177. if (isLooping)// Looping.
  178. {
  179. var animancerEvent = Events[_NextEventIndex];
  180. var eventTime = animancerEvent.normalizedTime * playDirectionFloat;
  181. var loopDelta = GetLoopDelta(_PreviousNormalizedTime, currentTime, eventTime);
  182. if (loopDelta == 0)
  183. return;
  184. // For each additional loop, invoke all events without needing to check their times.
  185. if (!InvokeAllEvents(Events, loopDelta - 1, playDirectionInt))
  186. return;
  187. var loopStartIndex = _NextEventIndex;
  188. Invoke:
  189. animancerEvent.DelayInvoke(Events.GetName(_NextEventIndex), State);
  190. if (!NextEventLooped(Events, playDirectionInt) ||
  191. _NextEventIndex == loopStartIndex)
  192. return;
  193. animancerEvent = Events[_NextEventIndex];
  194. eventTime = animancerEvent.normalizedTime * playDirectionFloat;
  195. if (loopDelta == GetLoopDelta(_PreviousNormalizedTime, currentTime, eventTime))
  196. goto Invoke;
  197. }
  198. else// Non-Looping.
  199. {
  200. while ((uint)_NextEventIndex < (uint)count)
  201. {
  202. var animancerEvent = Events[_NextEventIndex];
  203. var eventTime = animancerEvent.normalizedTime * playDirectionFloat;
  204. if (currentTime <= eventTime)
  205. return;
  206. animancerEvent.DelayInvoke(Events.GetName(_NextEventIndex), State);
  207. _NextEventIndex += playDirectionInt;
  208. }
  209. }
  210. }
  211. /************************************************************************************************************************/
  212. private void ValidateNextEventIndex(
  213. bool isLooping,
  214. ref float currentTime,
  215. out float playDirectionFloat,
  216. out int playDirectionInt)
  217. {
  218. if (currentTime < _PreviousNormalizedTime)// Playing Backwards.
  219. {
  220. var previousTime = _PreviousNormalizedTime;
  221. _PreviousNormalizedTime = -previousTime;
  222. currentTime = -currentTime;
  223. playDirectionFloat = -1;
  224. playDirectionInt = -1;
  225. if (_NextEventIndex == RecalculateEventIndex ||
  226. _WasPlayingForwards)
  227. {
  228. _NextEventIndex = Events.Count - 1;
  229. _WasPlayingForwards = false;
  230. if (isLooping)
  231. previousTime = AnimancerUtilities.Wrap01(previousTime);
  232. while (Events[_NextEventIndex].normalizedTime > previousTime)
  233. {
  234. _NextEventIndex--;
  235. if (_NextEventIndex < 0)
  236. {
  237. if (isLooping)
  238. _NextEventIndex = Events.Count - 1;
  239. break;
  240. }
  241. }
  242. Events.AssertNormalizedTimes(State, isLooping);
  243. }
  244. }
  245. else// Playing Forwards.
  246. {
  247. playDirectionFloat = 1;
  248. playDirectionInt = 1;
  249. if (_NextEventIndex == RecalculateEventIndex ||
  250. !_WasPlayingForwards)
  251. {
  252. _NextEventIndex = 0;
  253. _WasPlayingForwards = true;
  254. var previousTime = _PreviousNormalizedTime;
  255. if (isLooping)
  256. previousTime = AnimancerUtilities.Wrap01(previousTime);
  257. var max = Events.Count - 1;
  258. while (Events[_NextEventIndex].normalizedTime < previousTime)
  259. {
  260. _NextEventIndex++;
  261. if (_NextEventIndex > max)
  262. {
  263. if (isLooping)
  264. _NextEventIndex = 0;
  265. break;
  266. }
  267. }
  268. Events.AssertNormalizedTimes(State, isLooping);
  269. }
  270. }
  271. // This method could be slightly optimised for playback direction changes by using the current index
  272. // as the starting point instead of iterating from the edge of the sequence, but that would make it
  273. // significantly more complex for something that shouldn't happen very often and would only matter if
  274. // there are lots of events (in which case the optimisation would be tiny compared to the cost of
  275. // actually invoking all those events and running the rest of the application).
  276. }
  277. /************************************************************************************************************************/
  278. /// <summary>
  279. /// Calculates the number of times an event at `eventTime` should be invoked when the
  280. /// <see cref="AnimancerState.NormalizedTime"/> goes from `previousTime` to `nextTime` on a looping animation.
  281. /// </summary>
  282. private static int GetLoopDelta(float previousTime, float nextTime, float eventTime)
  283. {
  284. previousTime -= eventTime;
  285. nextTime -= eventTime;
  286. var previousLoopCount = Mathf.FloorToInt(previousTime);
  287. var nextLoopCount = Mathf.FloorToInt(nextTime);
  288. var loopCount = nextLoopCount - previousLoopCount;
  289. // Previous time must be inclusive.
  290. // And next time must be exclusive.
  291. // So if the previous time is exactly on a looped increment of the event time, count one more.
  292. // And if the next time is exactly on a looped increment of the event time, count one less.
  293. if (previousTime == previousLoopCount)
  294. loopCount++;
  295. if (nextTime == nextLoopCount)
  296. loopCount--;
  297. return loopCount;
  298. }
  299. /************************************************************************************************************************/
  300. private static int _MaximumFullLoopCount = 3;
  301. /// <summary>
  302. /// The maximum number of times a looping animation can trigger all of its events in a single frame.
  303. /// Default 3, Minimum 1.
  304. /// </summary>
  305. /// <remarks>
  306. /// This limit should only ever be reached when a state has a very short length and high speed.
  307. /// </remarks>
  308. public static int MaximumFullLoopCount
  309. {
  310. get => _MaximumFullLoopCount;
  311. set => _MaximumFullLoopCount = Math.Max(value, 1);
  312. }
  313. private bool InvokeAllEvents(Sequence events, int count, int playDirectionInt)
  314. {
  315. if (count > _MaximumFullLoopCount)
  316. count = _MaximumFullLoopCount;
  317. var loopStartIndex = _NextEventIndex;
  318. while (count-- > 0)
  319. {
  320. do
  321. {
  322. events[_NextEventIndex].DelayInvoke(events.GetName(_NextEventIndex), State);
  323. if (!NextEventLooped(events, playDirectionInt))
  324. return false;
  325. }
  326. while (_NextEventIndex != loopStartIndex);
  327. }
  328. return true;
  329. }
  330. /************************************************************************************************************************/
  331. private bool NextEventLooped(Sequence events, int playDirectionInt)
  332. {
  333. _NextEventIndex += playDirectionInt;
  334. var count = events.Count;
  335. if (_NextEventIndex >= count)
  336. _NextEventIndex = 0;
  337. else if (_NextEventIndex < 0)
  338. _NextEventIndex = count - 1;
  339. return true;
  340. }
  341. /************************************************************************************************************************/
  342. /// <summary>End events are triggered every frame after their time passes.</summary>
  343. /// <remarks>
  344. /// This ensures that assigning the event after the time has passed
  345. /// will still trigger it rather than leaving it playing indefinitely.
  346. /// </remarks>
  347. private void CheckEndEvent(float normalizedTime)
  348. {
  349. var endEvent = Events.EndEvent;
  350. if (endEvent.callback == null)
  351. return;
  352. if (normalizedTime > _PreviousNormalizedTime)// Playing Forwards.
  353. {
  354. var eventTime = float.IsNaN(endEvent.normalizedTime)
  355. ? 1
  356. : endEvent.normalizedTime;
  357. if (normalizedTime > eventTime)
  358. endEvent.DelayInvoke(EndEventName, State);
  359. }
  360. else// Playing Backwards.
  361. {
  362. var eventTime = float.IsNaN(endEvent.normalizedTime)
  363. ? 0
  364. : endEvent.normalizedTime;
  365. if (normalizedTime < eventTime)
  366. endEvent.DelayInvoke(EndEventName, State);
  367. }
  368. }
  369. /************************************************************************************************************************/
  370. /// <summary>Returns "<see cref="Dispatcher"/> (Target State)".</summary>
  371. public override string ToString()
  372. => State != null
  373. ? $"{nameof(Dispatcher)} ({State})"
  374. : $"{nameof(Dispatcher)} (No Target State)";
  375. /************************************************************************************************************************/
  376. /// <inheritdoc/>
  377. public void AppendDescription(StringBuilder text, string separator = "\n")
  378. {
  379. text.AppendField(separator, "State", State.GetPath());
  380. text.AppendField(separator, "IsLooping", State.IsLooping);
  381. text.AppendField(separator, "PreviousNormalizedTime", _PreviousNormalizedTime);
  382. text.AppendField(separator, "NextEventIndex", _NextEventIndex);
  383. text.AppendField(separator, "SequenceVersion", _SequenceVersion);
  384. text.AppendField(separator, "WasPlayingForwards", _WasPlayingForwards);
  385. }
  386. /************************************************************************************************************************/
  387. }
  388. }
  389. }