CinemachineImpulseManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using System;
  2. using System.Collections.Generic;
  3. using Cinemachine.Utility;
  4. using UnityEngine;
  5. namespace Cinemachine
  6. {
  7. /// <summary>
  8. /// Property applied to CinemachineImpulseManager.EnvelopeDefinition.
  9. /// Used for custom drawing in the inspector.
  10. /// </summary>
  11. public sealed class CinemachineImpulseEnvelopePropertyAttribute : PropertyAttribute {}
  12. /// <summary>
  13. /// Property applied to CinemachineImpulseManager Channels.
  14. /// Used for custom drawing in the inspector.
  15. /// </summary>
  16. public sealed class CinemachineImpulseChannelPropertyAttribute : PropertyAttribute {}
  17. /// <summary>
  18. /// This is a singleton object that manages all Impulse Events generated by the Cinemachine
  19. /// Impulse module. This singleton owns and manages all ImpulseEvent objectss.
  20. /// </summary>
  21. [DocumentationSorting(DocumentationSortingAttribute.Level.API)]
  22. public class CinemachineImpulseManager
  23. {
  24. private CinemachineImpulseManager() {}
  25. private static CinemachineImpulseManager sInstance = null;
  26. /// <summary>Get the singleton instance</summary>
  27. public static CinemachineImpulseManager Instance
  28. {
  29. get
  30. {
  31. if (sInstance == null)
  32. sInstance = new CinemachineImpulseManager();
  33. return sInstance;
  34. }
  35. }
  36. [RuntimeInitializeOnLoadMethod]
  37. static void InitializeModule()
  38. {
  39. if (sInstance != null)
  40. sInstance.Clear();
  41. }
  42. const float Epsilon = UnityVectorExtensions.Epsilon;
  43. /// <summary>This defines the time-envelope of the signal.
  44. /// Thie raw signal will be scaled to fit inside the envelope.</summary>
  45. [Serializable]
  46. public struct EnvelopeDefinition
  47. {
  48. /// <summary>Normalized curve defining the shape of the start of the envelope.</summary>
  49. [Tooltip("Normalized curve defining the shape of the start of the envelope. If blank a default curve will be used")]
  50. public AnimationCurve m_AttackShape;
  51. /// <summary>Normalized curve defining the shape of the end of the envelope.</summary>
  52. [Tooltip("Normalized curve defining the shape of the end of the envelope. If blank a default curve will be used")]
  53. public AnimationCurve m_DecayShape;
  54. /// <summary>Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0</summary>
  55. [Tooltip("Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0.")]
  56. public float m_AttackTime; // Must be >= 0
  57. /// <summary>Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0.</summary>
  58. [Tooltip("Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0.")]
  59. public float m_SustainTime; // Must be >= 0
  60. /// <summary>Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0.</summary>
  61. [Tooltip("Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0.")]
  62. public float m_DecayTime; // Must be >= 0
  63. /// <summary>If checked, signal amplitude scaling will also be applied to the time envelope of the signal. Bigger signals will last longer</summary>
  64. [Tooltip("If checked, signal amplitude scaling will also be applied to the time envelope of the signal. Stronger signals will last longer.")]
  65. public bool m_ScaleWithImpact;
  66. /// <summary>If true, then duration is infinite.</summary>
  67. [Tooltip("If true, then duration is infinite.")]
  68. public bool m_HoldForever;
  69. /// <summary>Get an envelope with default values.</summary>
  70. public static EnvelopeDefinition Default()
  71. {
  72. return new EnvelopeDefinition { m_DecayTime = 0.7f, m_SustainTime = 0.2f, m_ScaleWithImpact = true };
  73. }
  74. /// <summary>Duration of the envelope, in seconds. If negative, then duration is infinite.</summary>
  75. public float Duration
  76. {
  77. get
  78. {
  79. if (m_HoldForever)
  80. return -1;
  81. return m_AttackTime + m_SustainTime + m_DecayTime;
  82. }
  83. }
  84. /// <summary>
  85. /// Get the value of the tenvelope at a given time relative to the envelope start.
  86. /// </summary>
  87. /// <param name="offset">Time in seconds from the envelope start</param>
  88. /// <returns>Envelope amplitude. This will range from 0...1</returns>
  89. public float GetValueAt(float offset)
  90. {
  91. if (offset >= 0)
  92. {
  93. if (offset < m_AttackTime && m_AttackTime > Epsilon)
  94. {
  95. if (m_AttackShape == null || m_AttackShape.length < 2)
  96. return Damper.Damp(1, m_AttackTime, offset);
  97. return m_AttackShape.Evaluate(offset / m_AttackTime);
  98. }
  99. offset -= m_AttackTime;
  100. if (m_HoldForever || offset < m_SustainTime)
  101. return 1;
  102. offset -= m_SustainTime;
  103. if (offset < m_DecayTime && m_DecayTime > Epsilon)
  104. {
  105. if (m_DecayShape == null || m_DecayShape.length < 2)
  106. return 1 - Damper.Damp(1, m_DecayTime, offset);
  107. return m_DecayShape.Evaluate(offset / m_DecayTime);
  108. }
  109. }
  110. return 0;
  111. }
  112. /// <summary>
  113. /// Change the envelope so that it stops at a specific offset from its start time.
  114. /// Use this to extend or cut short an existing envelope, while respecting the
  115. /// attack and decay as much as possible.
  116. /// </summary>
  117. /// <param name="offset">When to stop the envelope</param>
  118. /// <param name="forceNoDecay">If true, enevlope will not decay, but cut off instantly</param>
  119. public void ChangeStopTime(float offset, bool forceNoDecay)
  120. {
  121. if (offset < 0)
  122. offset = 0;
  123. if (offset < m_AttackTime)
  124. m_AttackTime = 0; // How to prevent pop? GML
  125. m_SustainTime = offset - m_AttackTime;
  126. if (forceNoDecay)
  127. m_DecayTime = 0;
  128. }
  129. /// <summary>
  130. /// Set the envelop times to 0 and the shapes to default.
  131. /// </summary>
  132. public void Clear()
  133. {
  134. m_AttackShape = m_DecayShape = null;
  135. m_AttackTime = m_SustainTime = m_DecayTime = 0;
  136. }
  137. /// <summary>
  138. /// Call from OnValidate to ensure that envelope values are sane
  139. /// </summary>
  140. public void Validate()
  141. {
  142. m_AttackTime = Mathf.Max(0, m_AttackTime);
  143. m_DecayTime = Mathf.Max(0, m_DecayTime);
  144. m_SustainTime = Mathf.Max(0, m_SustainTime);
  145. }
  146. }
  147. /// <summary>Describes an event that generates an impulse signal on one or more channels.
  148. /// The event has a location in space, a start time, a duration, and a signal. The signal
  149. /// will dissipate as the distance from the event location increases.</summary>
  150. public class ImpulseEvent
  151. {
  152. /// <summary>Start time of the event.</summary>
  153. [Tooltip("Start time of the event.")]
  154. public float m_StartTime;
  155. /// <summary>Time-envelope of the signal.</summary>
  156. [Tooltip("Time-envelope of the signal.")]
  157. public EnvelopeDefinition m_Envelope;
  158. /// <summary>Raw signal source. The ouput of this will be scaled to fit in the envelope.</summary>
  159. [Tooltip("Raw signal source. The ouput of this will be scaled to fit in the envelope.")]
  160. public ISignalSource6D m_SignalSource;
  161. /// <summary>Worldspace origin of the signal.</summary>
  162. [Tooltip("Worldspace origin of the signal.")]
  163. public Vector3 m_Position;
  164. /// <summary>Radius around the signal origin that has full signal value. Distance dissipation begins after this distance.</summary>
  165. [Tooltip("Radius around the signal origin that has full signal value. Distance dissipation begins after this distance.")]
  166. public float m_Radius;
  167. /// <summary>How the signal behaves as the listener moves away from the origin.</summary>
  168. public enum DirectionMode
  169. {
  170. /// <summary>Signal direction remains constant everywhere.</summary>
  171. Fixed,
  172. /// <summary>Signal is rotated in the direction of the source.</summary>
  173. RotateTowardSource
  174. }
  175. /// <summary>How the signal direction behaves as the listener moves away from the source.</summary>
  176. [Tooltip("How the signal direction behaves as the listener moves away from the source.")]
  177. public DirectionMode m_DirectionMode = DirectionMode.Fixed;
  178. /// <summary>Channels on which this event will broadcast its signal.</summary>
  179. [Tooltip("Channels on which this event will broadcast its signal.")]
  180. public int m_Channel;
  181. /// <summary>How the signal dissipates with distance.</summary>
  182. public enum DissipationMode
  183. {
  184. /// <summary>Simple linear interpolation to zero over the dissipation distance.</summary>
  185. LinearDecay,
  186. /// <summary>Ease-in-ease-out dissipation over the dissipation distance.</summary>
  187. SoftDecay,
  188. /// <summary>Half-life decay, hard out from full and ease into 0 over the dissipation distance.</summary>
  189. ExponentialDecay
  190. }
  191. /// <summary>How the signal dissipates with distance.</summary>
  192. [Tooltip("How the signal dissipates with distance.")]
  193. public DissipationMode m_DissipationMode;
  194. /// <summary>Distance over which the dissipation occurs. Must be >= 0.</summary>
  195. [Tooltip("Distance over which the dissipation occurs. Must be >= 0.")]
  196. public float m_DissipationDistance;
  197. /// <summary>
  198. /// The speed (m/s) at which the impulse propagates through space. High speeds
  199. /// allow listeners to react instantaneously, while slower speeds allow listeres in the
  200. /// scene to react as if to a wave spreading from the source.
  201. /// </summary>
  202. [Tooltip("The speed (m/s) at which the impulse propagates through space. High speeds "
  203. + "allow listeners to react instantaneously, while slower speeds allow listeres in the "
  204. + "scene to react as if to a wave spreading from the source.")]
  205. public float m_PropagationSpeed;
  206. /// <summary>Returns true if the event is no longer generating a signal because its time has expired</summary>
  207. public bool Expired
  208. {
  209. get
  210. {
  211. var d = m_Envelope.Duration;
  212. var maxDistance = m_Radius + m_DissipationDistance;
  213. float time = Instance.CurrentTime - maxDistance / Mathf.Max(1, m_PropagationSpeed);
  214. return d > 0 && m_StartTime + d <= time;
  215. }
  216. }
  217. /// <summary>Cancel the event at the supplied time</summary>
  218. /// <param name="time">The time at which to cancel the event</param>
  219. /// <param name="forceNoDecay">If true, event will be cut immediately at the time,
  220. /// otherwise its envelope's decay curve will begin at the cancel time</param>
  221. public void Cancel(float time, bool forceNoDecay)
  222. {
  223. m_Envelope.m_HoldForever = false;
  224. m_Envelope.ChangeStopTime(time - m_StartTime, forceNoDecay);
  225. }
  226. /// <summary>Calculate the the decay applicable at a given distance from the impact point</summary>
  227. /// <returns>Scale factor 0...1</returns>
  228. public float DistanceDecay(float distance)
  229. {
  230. float radius = Mathf.Max(m_Radius, 0);
  231. if (distance < radius)
  232. return 1;
  233. distance -= radius;
  234. if (distance >= m_DissipationDistance)
  235. return 0;
  236. switch (m_DissipationMode)
  237. {
  238. default:
  239. case DissipationMode.LinearDecay:
  240. return Mathf.Lerp(1, 0, distance / m_DissipationDistance);
  241. case DissipationMode.SoftDecay:
  242. return 0.5f * (1 + Mathf.Cos(Mathf.PI * (distance / m_DissipationDistance)));
  243. case DissipationMode.ExponentialDecay:
  244. return 1 - Damper.Damp(1, m_DissipationDistance, distance);
  245. }
  246. }
  247. /// <summary>Get the signal that a listener at a given position would perceive</summary>
  248. /// <param name="listenerPosition">The listener's position in world space</param>
  249. /// <param name="use2D">True if distance calculation should ignore Z</param>
  250. /// <param name="pos">The position impulse signal</param>
  251. /// <param name="rot">The rotation impulse signal</param>
  252. /// <returns>true if non-trivial signal is returned</returns>
  253. public bool GetDecayedSignal(
  254. Vector3 listenerPosition, bool use2D, out Vector3 pos, out Quaternion rot)
  255. {
  256. if (m_SignalSource != null)
  257. {
  258. float distance = use2D ? Vector2.Distance(listenerPosition, m_Position)
  259. : Vector3.Distance(listenerPosition, m_Position);
  260. float time = Instance.CurrentTime - m_StartTime
  261. - distance / Mathf.Max(1, m_PropagationSpeed);
  262. float scale = m_Envelope.GetValueAt(time) * DistanceDecay(distance);
  263. if (scale != 0)
  264. {
  265. m_SignalSource.GetSignal(time, out pos, out rot);
  266. pos *= scale;
  267. rot = Quaternion.SlerpUnclamped(Quaternion.identity, rot, scale);
  268. if (m_DirectionMode == DirectionMode.RotateTowardSource && distance > Epsilon)
  269. {
  270. Quaternion q = Quaternion.FromToRotation(Vector3.up, listenerPosition - m_Position);
  271. if (m_Radius > Epsilon)
  272. {
  273. float t = Mathf.Clamp01(distance / m_Radius);
  274. q = Quaternion.Slerp(
  275. q, Quaternion.identity, Mathf.Cos(Mathf.PI * t / 2));
  276. }
  277. pos = q * pos;
  278. }
  279. return true;
  280. }
  281. }
  282. pos = Vector3.zero;
  283. rot = Quaternion.identity;
  284. return false;
  285. }
  286. /// <summary>Reset the event to a default state</summary>
  287. public void Clear()
  288. {
  289. m_Envelope.Clear();
  290. m_StartTime = 0;
  291. m_SignalSource = null;
  292. m_Position = Vector3.zero;
  293. m_Channel = 0;
  294. m_Radius = 0;
  295. m_DissipationDistance = 100;
  296. m_DissipationMode = DissipationMode.ExponentialDecay;
  297. }
  298. /// <summary>Don't create them yourself. Use CinemachineImpulseManager.NewImpulseEvent().</summary>
  299. internal ImpulseEvent() {}
  300. }
  301. List<ImpulseEvent> m_ExpiredEvents;
  302. List<ImpulseEvent> m_ActiveEvents;
  303. /// <summary>Get the signal perceived by a listener at a geven location</summary>
  304. /// <param name="listenerLocation">Where the listener is, in world coords</param>
  305. /// <param name="distance2D">True if distance calculation should ignore Z</param>
  306. /// <param name="channelMask">Only Impulse signals on channels in this mask will be considered</param>
  307. /// <param name="pos">The combined position impulse signal resulting from all signals active on the specified channels</param>
  308. /// <param name="rot">The combined rotation impulse signal resulting from all signals active on the specified channels</param>
  309. /// <returns>true if non-trivial signal is returned</returns>
  310. public bool GetImpulseAt(
  311. Vector3 listenerLocation, bool distance2D, int channelMask,
  312. out Vector3 pos, out Quaternion rot)
  313. {
  314. bool nontrivialResult = false;
  315. pos = Vector3.zero;
  316. rot = Quaternion.identity;
  317. if (m_ActiveEvents != null)
  318. {
  319. for (int i = m_ActiveEvents.Count - 1; i >= 0; --i)
  320. {
  321. ImpulseEvent e = m_ActiveEvents[i];
  322. // Prune invalid or expired events
  323. if (e == null || e.Expired)
  324. {
  325. m_ActiveEvents.RemoveAt(i);
  326. if (e != null)
  327. {
  328. // Recycle it
  329. if (m_ExpiredEvents == null)
  330. m_ExpiredEvents = new List<ImpulseEvent>();
  331. e.Clear();
  332. m_ExpiredEvents.Add(e);
  333. }
  334. }
  335. else if ((e.m_Channel & channelMask) != 0)
  336. {
  337. Vector3 pos0 = Vector3.zero;
  338. Quaternion rot0 = Quaternion.identity;
  339. if (e.GetDecayedSignal(listenerLocation, distance2D, out pos0, out rot0))
  340. {
  341. nontrivialResult = true;
  342. pos += pos0;
  343. rot *= rot0;
  344. }
  345. }
  346. }
  347. }
  348. return nontrivialResult;
  349. }
  350. /// <summary>Set this to ignore time scaling so impulses can progress while the game is paused</summary>
  351. public bool IgnoreTimeScale { get; set; }
  352. /// <summary>
  353. /// This is the Impulse system's current time.
  354. /// Takes into accoount whether impulse is ignoring time scale.
  355. /// </summary>
  356. public float CurrentTime { get { return IgnoreTimeScale ? Time.realtimeSinceStartup : CinemachineCore.CurrentTime; } }
  357. /// <summary>Get a new ImpulseEvent</summary>
  358. public ImpulseEvent NewImpulseEvent()
  359. {
  360. ImpulseEvent e;
  361. if (m_ExpiredEvents == null || m_ExpiredEvents.Count == 0)
  362. return new ImpulseEvent();
  363. e = m_ExpiredEvents[m_ExpiredEvents.Count-1];
  364. m_ExpiredEvents.RemoveAt(m_ExpiredEvents.Count-1);
  365. return e;
  366. }
  367. /// <summary>Activate an impulse event, so that it may begin broadcasting its signal</summary>
  368. /// Events will be automatically removed after they expire.
  369. /// You can tweak the ImpulseEvent fields dynamically if you keep a pointer to it.
  370. public void AddImpulseEvent(ImpulseEvent e)
  371. {
  372. if (m_ActiveEvents == null)
  373. m_ActiveEvents = new List<ImpulseEvent>();
  374. if (e != null)
  375. {
  376. e.m_StartTime = CurrentTime;
  377. m_ActiveEvents.Add(e);
  378. }
  379. }
  380. /// <summary>Immediately terminate all active impulse signals</summary>
  381. public void Clear()
  382. {
  383. if (m_ActiveEvents != null)
  384. {
  385. for (int i = 0; i < m_ActiveEvents.Count; ++i)
  386. m_ActiveEvents[i].Clear();
  387. m_ActiveEvents.Clear();
  388. }
  389. }
  390. }
  391. }