MotionAwaiter.cs
Runtime/Lifecycle/MotionAwaiter.cs
1 using System;
2 using System.Runtime.CompilerServices;
3 using System.Threading;
4 using System.Threading.Tasks;
5 using System.Threading.Tasks.Sources;
6 using UnityEngine;
7
8 namespace MeatMotion
9 {
10 public readonly struct MotionAwaiter : ICriticalNotifyCompletion
11 {
12 readonly MotionHandle handle;
13 public MotionAwaiter(MotionHandle handle) => this.handle = handle;
14 public MotionAwaiter GetAwaiter() => this;
15 public bool IsCompleted => !handle.IsActive();
16 public void GetResult() { }
17 public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation);
18 public void UnsafeOnCompleted(Action continuation)
19 {
20 if (continuation == null) return;
21 if (handle.Node is { Active: true } node) new Continuation(continuation).Attach(node);
22 else continuation();
23 }
24
25 sealed class Continuation : MotionObserver
26 {
27 readonly Action action;
28 internal Continuation(Action action) => this.action = action;
29 protected override void Signal(bool completed) => action();
30 }
31 }
32
33 // Observers are one-shot. Detaching a whole generation before user code allows
34 // a preserved motion to rewind and acquire fresh waiters inside its callback.
35 internal abstract class MotionObserver
36 {
37 MotionNode owner;
38 MotionObserver previous, next;
39
40 internal void Attach(MotionNode node)
41 {
42 owner = node;
43 previous = node.LastObserver;
44 if (previous == null) node.Observers = this;
45 else previous.next = this;
46 node.LastObserver = this;
47 }
48
49 protected void Unlink()
50 {
51 if (owner == null) return;
52 if (previous == null) owner.Observers = next;
53 else previous.next = next;
54 if (next == null) owner.LastObserver = previous;
55 else next.previous = previous;
56 owner = null;
57 previous = next = null;
58 }
59
60 internal static MotionObserver Detach(MotionNode node)
61 {
62 var first = node.Observers;
63 node.Observers = node.LastObserver = null;
64 for (var o = first; o != null; o = o.next) { o.owner = null; o.previous = null; }
65 return first;
66 }
67
68 internal static void Finish(MotionObserver first, bool completed)
69 {
70 while (first != null)
71 {
72 var current = first;
73 first = current.next;
74 current.next = null;
75 try { current.Signal(completed); }
76 catch (Exception ex) { MotionDispatcher.Report(ex); }
77 }
78 }
79
80 internal static void Forget(MotionNode node)
81 {
82 var current = Detach(node);
83 while (current != null)
84 {
85 var next = current.next;
86 current.next = null;
87 current.OnReset();
88 current = next;
89 }
90 }
91 protected virtual void OnReset() { }
92 protected abstract void Signal(bool completed);
93 }
94
95 // Most animation waits have no external token. A consumed source can be used
96 // again without allocating a Task, registration, or callback delegate.
97 #if UNITY_6000_7_OR_NEWER
98 [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // A pool of finished waits.
99 #endif
100 internal sealed class TokenlessValueWait : MotionObserver, IValueTaskSource
101 {
102 [ThreadStatic] static TokenlessValueWait pool;
103 TokenlessValueWait nextFree;
104 ManualResetValueTaskSourceCore<bool> source;
105 bool linkCancellation;
106
107 internal static ValueTask Create(MotionNode node, bool linked)
108 {
109 var wait = pool ?? new TokenlessValueWait();
110 pool = wait.nextFree;
111 wait.nextFree = null;
112 wait.linkCancellation = linked;
113 wait.Attach(node);
114 return new ValueTask(wait, wait.source.Version);
115 }
116
117 protected override void Signal(bool completed)
118 {
119 if (completed || !linkCancellation) source.SetResult(true);
120 else source.SetException(new OperationCanceledException());
121 }
122
123 public ValueTaskSourceStatus GetStatus(short token) => source.GetStatus(token);
124 public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
125 => source.OnCompleted(continuation, state, token, flags);
126 public void GetResult(short token)
127 {
128 if (source.GetStatus(token) == ValueTaskSourceStatus.Pending) throw new InvalidOperationException("Motion is still active.");
129 try { source.GetResult(token); }
130 finally
131 {
132 source.Reset();
133 nextFree = pool;
134 pool = this;
135 }
136 }
137 }
138
139 internal sealed class MotionWait : MotionObserver
140 {
141 readonly TaskCompletionSource<bool> task;
142 readonly AwaitableCompletionSource unity;
143 readonly Action<bool, CancellationToken> complete;
144 CancellationTokenRegistration registration;
145 SynchronizationContext context;
146 int thread;
147 MotionHandle handle;
148 CancellationToken token;
149 CancelBehavior behavior;
150 bool linkCancellation, finished;
151 internal MotionWait() => task = new TaskCompletionSource<bool>();
152 internal MotionWait(Action<bool, CancellationToken> complete) => this.complete = complete;
153 internal MotionWait(AwaitableCompletionSource source) => unity = source;
154 internal ValueTask ValueTask => new ValueTask(task.Task);
155
156 internal void Start(MotionHandle motion, CancelBehavior cancelBehavior, bool linked, CancellationToken cancellationToken)
157 {
158 handle = motion;
159 behavior = cancelBehavior;
160 linkCancellation = linked;
161 token = cancellationToken;
162 Attach(handle.RequireValid());
163 if (!token.CanBeCanceled) return;
164 context = SynchronizationContext.Current;
165 thread = Environment.CurrentManagedThreadId;
166 registration = token.Register(static state => ((MotionWait)state).TokenCanceled(), this);
167 if (finished) registration.Dispose(); // Register can invoke synchronously.
168 }
169
170 void TokenCanceled()
171 {
172 if (thread != Environment.CurrentManagedThreadId && context != null)
173 context.Post(static state => ((MotionWait)state).CancelFromToken(), this);
174 else CancelFromToken();
175 }
176
177 void CancelFromToken()
178 {
179 if (finished) return;
180 Unlink();
181 try
182 {
183 if (behavior == CancelBehavior.Cancel) handle.TryCancel();
184 else if (behavior == CancelBehavior.Complete) handle.TryComplete();
185 }
186 finally { Resolve(true); }
187 }
188
189 protected override void OnReset()
190 {
191 // Dispatcher.Reset discards callbacks, including await continuations.
192 finished = true;
193 registration.Dispose();
194 }
195
196 protected override void Signal(bool completed) => Resolve(token.IsCancellationRequested || (!completed && linkCancellation));
197 void Resolve(bool canceled)
198 {
199 if (finished) return;
200 finished = true;
201 registration.Dispose();
202 if (complete != null) complete(canceled, token);
203 else if (unity != null)
204 {
205 if (canceled) unity.SetCanceled();
206 else unity.SetResult();
207 }
208 else if (canceled) task.TrySetCanceled(token);
209 else task.TrySetResult(true);
210 }
211 }
212 }