MotionUpdateDriver.cs
Runtime/Scheduling/MotionUpdateDriver.cs
1 using System;
2 using System.Collections.Generic;
3 using Unity.Profiling;
4 using UnityEngine;
5 using UnityEngine.LowLevel;
6 using Loop = UnityEngine.PlayerLoop;
7
8 [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MeatMotion.UI")]
9 [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MeatMotion.Editor")]
10 [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MeatMotion.Integrations.UniTask")]
11
12 namespace MeatMotion
13 {
14 public static class MotionLoopRunners
15 {
16 public struct Initialization { }
17 public struct EarlyUpdate { }
18 public struct FixedUpdate { }
19 public struct PreUpdate { }
20 public struct Update { }
21 public struct PreLateUpdate { }
22 public struct PostLateUpdate { }
23 public struct TimeUpdate { }
24 }
25
26 [AddComponentMenu("")]
27 #if UNITY_6000_7_OR_NEWER
28 [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // EndSession resets the clocks. AfterUpdate keeps its subscribers.
29 #endif
30 public sealed class MotionUpdateDriver : MonoBehaviour
31 {
32 sealed class PhaseClock
33 {
34 readonly bool fixedStep, editor;
35 internal MotionWorld World;
36 internal void StartClock() => Read(out scaled, out unscaled, out realtime);
37 double scaled, unscaled, realtime;
38
39 internal PhaseClock(bool fixedStep = false, bool editor = false)
40 {
41 this.fixedStep = fixedStep;
42 this.editor = editor;
43 }
44
45 void Read(out double s, out double u, out double r)
46 {
47 r = Time.realtimeSinceStartupAsDouble;
48 #if UNITY_EDITOR
49 if (editor) { s = u = UnityEditor.EditorApplication.timeSinceStartup; return; }
50 #endif
51 s = fixedStep ? Time.fixedTimeAsDouble : Time.timeAsDouble;
52 u = fixedStep ? Time.fixedUnscaledTimeAsDouble : Time.unscaledTimeAsDouble;
53 }
54
55 internal void Run()
56 {
57 if (World == null || World.IsDisposed) return;
58 Read(out double s, out double u, out double r);
59 double ds = s - scaled, du = u - unscaled, dr = r - realtime;
60 scaled = s; unscaled = u; realtime = r;
61 World.TickClocks(ds, du, dr);
62 }
63
64 internal void Clear()
65 {
66 if (World == null || World.IsDisposed) return;
67 World.ResetWithoutCallbacks();
68 Read(out scaled, out unscaled, out realtime);
69 }
70
71 }
72
73 sealed class Phase
74 {
75 readonly bool fixedStep, editor;
76 readonly Dictionary<Type, PhaseClock> byType = new Dictionary<Type, PhaseClock>();
77 // Reserving storage must not start the clock or change callback order.
78 readonly Dictionary<Type, MotionWorld> reserved = new Dictionary<Type, MotionWorld>();
79 readonly List<PhaseClock> active = new List<PhaseClock>();
80 readonly List<MotionWorld> typedWorlds = new List<MotionWorld>();
81 MotionWorld controller, floatWorld;
82
83 internal Phase(bool fixedStep = false, bool editor = false)
84 { this.fixedStep = fixedStep; this.editor = editor; }
85
86 internal MotionWorld Get(Type type)
87 {
88 if (type == FloatMotionBuilder.FloatStorage && floatWorld != null && !floatWorld.IsDisposed)
89 return floatWorld;
90 bool native = type == null;
91 type ??= typeof(FloatMotionBuilder);
92 if (!byType.TryGetValue(type, out var clock))
93 {
94 clock = new PhaseClock(fixedStep, editor);
95 byType.Add(type, clock);
96 active.Add(clock);
97 }
98 if (clock.World != null && !clock.World.IsDisposed) return clock.World;
99 if (!reserved.TryGetValue(type, out var world)) world = new MotionWorld();
100 else reserved.Remove(type);
101 clock.World = world;
102 if (type == FloatMotionBuilder.FloatStorage) floatWorld = world;
103 clock.StartClock();
104 world.AutomaticPhase = this;
105 if (native)
106 {
107 controller = world;
108 world.ScheduledWorlds = typedWorlds.ToArray();
109 }
110 else
111 {
112 typedWorlds.RemoveAll(w => w.IsDisposed);
113 typedWorlds.Add(world);
114 if (controller != null && !controller.IsDisposed) controller.ScheduledWorlds = typedWorlds.ToArray();
115 }
116 return world;
117 }
118
119 internal void Run()
120 {
121 int count = active.Count;
122 for (int i = 0; i < count; i++) active[i].Run();
123 }
124
125 internal void Clear()
126 {
127 foreach (var clock in active) clock.Clear();
128 }
129
130 internal void Reserve(Type type, int capacity)
131 {
132 if (byType.TryGetValue(type, out var clock) && clock.World != null && !clock.World.IsDisposed)
133 clock.World.EnsureCapacity(capacity);
134 else if (reserved.TryGetValue(type, out var world)) world.EnsureCapacity(capacity);
135 else reserved.Add(type, new MotionWorld(capacity));
136 }
137 }
138
139 static readonly Type[] phases = { typeof(Loop.Initialization), typeof(Loop.EarlyUpdate), typeof(Loop.FixedUpdate), typeof(Loop.PreUpdate), typeof(Loop.Update), typeof(Loop.PreLateUpdate), typeof(Loop.PostLateUpdate), typeof(Loop.TimeUpdate) };
140 static readonly Type[] markers = { typeof(MotionLoopRunners.Initialization), typeof(MotionLoopRunners.EarlyUpdate), typeof(MotionLoopRunners.FixedUpdate), typeof(MotionLoopRunners.PreUpdate), typeof(MotionLoopRunners.Update), typeof(MotionLoopRunners.PreLateUpdate), typeof(MotionLoopRunners.PostLateUpdate), typeof(MotionLoopRunners.TimeUpdate) };
141 static readonly Phase[] clocks = CreateClocks();
142 static Phase[] CreateClocks()
143 {
144 var result = new Phase[phases.Length];
145 for (int i = 0; i < result.Length; i++) result[i] = new Phase(i == (int)LoopPhase.FixedUpdate);
146 return result;
147 }
148
149 #if UNITY_EDITOR
150 static readonly Phase editClock = new Phase(editor: true);
151 internal static MotionWorld EditorWorld(Type type) => editClock.Get(type);
152 internal static void TickEditor() => editClock.Run();
153 #endif
154
155 internal static event Action AfterUpdate;
156 internal static void NotifyAfterUpdate() => AfterUpdate?.Invoke();
157
158 static readonly ProfilerMarker updateMarker = new ProfilerMarker("MeatMotion.Update");
159
160 static void RunUpdate()
161 {
162 using (updateMarker.Auto()) clocks[(int)LoopPhase.Update].Run();
163 NotifyAfterUpdate();
164 }
165
166 internal static MotionWorld World => GetWorld(LoopPhase.Update);
167 internal static MotionWorld GetWorld(LoopPhase phase, Type type = null)
168 {
169 #if UNITY_EDITOR
170 if (!Application.isPlaying) return editClock.Get(type);
171 #endif
172 return clocks[(int)phase].Get(type);
173 }
174
175 [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
176 static void Install()
177 {
178 Clear();
179 var loop = PlayerLoop.GetCurrentPlayerLoop();
180 var entries = loop.subSystemList;
181 for (int i = 0; i < entries.Length; i++)
182 {
183 int index = Array.IndexOf(phases, entries[i].type);
184 if (index < 0) continue;
185 var marker = markers[index];
186 var old = entries[i].subSystemList ?? Array.Empty<PlayerLoopSystem>();
187 int count = 1;
188 foreach (var child in old) if (child.type != marker) count++;
189 var children = new PlayerLoopSystem[count];
190 children[0] = new PlayerLoopSystem { type = marker, updateDelegate = index == (int)LoopPhase.Update ? RunUpdate : clocks[index].Run };
191 int pos = 1;
192 foreach (var child in old) if (child.type != marker) children[pos++] = child;
193 entries[i].subSystemList = children;
194 }
195 PlayerLoop.SetPlayerLoop(loop);
196 }
197
198 internal static void Clear()
199 {
200 foreach (var clock in clocks) clock.Clear();
201 #if UNITY_EDITOR
202 editClock.Clear();
203 #endif
204 }
205
206 #if UNITY_EDITOR
207 // Play Mode is starting or stopping. With "Reload Domain" off nothing else separates two
208 // sessions: no motion or clock may reach the next one. Settings stay.
209 internal static void EndSession()
210 {
211 Clear();
212 MotionWorld.ResetAll();
213 ManualMotionDispatcher.Default.Reset();
214 }
215 #endif
216
217 internal static void EnsureCapacity(Type type, int capacity)
218 {
219 if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
220 foreach (var clock in clocks) clock.Reserve(type, capacity);
221 #if UNITY_EDITOR
222 editClock.Reserve(type, capacity);
223 #endif
224 }
225 }
226 }