using System; using System.Collections.Generic; using Cinemachine.Utility; using UnityEngine; namespace Cinemachine { /// /// Property applied to CinemachineImpulseManager.EnvelopeDefinition. /// Used for custom drawing in the inspector. This attribute is obsolete and not used. /// public sealed class CinemachineImpulseEnvelopePropertyAttribute : PropertyAttribute {} /// /// Property applied to CinemachineImpulseManager Channels. /// Used for custom drawing in the inspector. /// public sealed class CinemachineImpulseChannelPropertyAttribute : PropertyAttribute {} /// /// This is a singleton object that manages all Impulse Events generated by the Cinemachine /// Impulse module. This singleton owns and manages all ImpulseEvent objectss. /// [DocumentationSorting(DocumentationSortingAttribute.Level.API)] public class CinemachineImpulseManager { private CinemachineImpulseManager() {} private static CinemachineImpulseManager sInstance = null; /// Get the singleton instance public static CinemachineImpulseManager Instance { get { if (sInstance == null) sInstance = new CinemachineImpulseManager(); return sInstance; } } [RuntimeInitializeOnLoadMethod] static void InitializeModule() { if (sInstance != null) sInstance.Clear(); } const float Epsilon = UnityVectorExtensions.Epsilon; /// This defines the time-envelope of the signal. /// Thie raw signal will be scaled to fit inside the envelope. [Serializable] public struct EnvelopeDefinition { /// Normalized curve defining the shape of the start of the envelope. [Tooltip("Normalized curve defining the shape of the start of the envelope. If blank a default curve will be used")] public AnimationCurve m_AttackShape; /// Normalized curve defining the shape of the end of the envelope. [Tooltip("Normalized curve defining the shape of the end of the envelope. If blank a default curve will be used")] public AnimationCurve m_DecayShape; /// Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0 [Tooltip("Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0.")] public float m_AttackTime; // Must be >= 0 /// Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0. [Tooltip("Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0.")] public float m_SustainTime; // Must be >= 0 /// Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0. [Tooltip("Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0.")] public float m_DecayTime; // Must be >= 0 /// If checked, signal amplitude scaling will also be applied to the time envelope of the signal. Bigger signals will last longer [Tooltip("If checked, signal amplitude scaling will also be applied to the time envelope of the signal. Stronger signals will last longer.")] public bool m_ScaleWithImpact; /// If true, then duration is infinite. [Tooltip("If true, then duration is infinite.")] public bool m_HoldForever; /// Get an envelope with default values. /// An event with default values public static EnvelopeDefinition Default() { return new EnvelopeDefinition { m_DecayTime = 0.7f, m_SustainTime = 0.2f, m_ScaleWithImpact = true }; } /// Duration of the envelope, in seconds. If negative, then duration is infinite. public float Duration { get { if (m_HoldForever) return -1; return m_AttackTime + m_SustainTime + m_DecayTime; } } /// /// Get the value of the tenvelope at a given time relative to the envelope start. /// /// Time in seconds from the envelope start /// Envelope amplitude. This will range from 0...1 public float GetValueAt(float offset) { if (offset >= 0) { if (offset < m_AttackTime && m_AttackTime > Epsilon) { if (m_AttackShape == null || m_AttackShape.length < 2) return Damper.Damp(1, m_AttackTime, offset); return m_AttackShape.Evaluate(offset / m_AttackTime); } offset -= m_AttackTime; if (m_HoldForever || offset < m_SustainTime) return 1; offset -= m_SustainTime; if (offset < m_DecayTime && m_DecayTime > Epsilon) { if (m_DecayShape == null || m_DecayShape.length < 2) return 1 - Damper.Damp(1, m_DecayTime, offset); return m_DecayShape.Evaluate(offset / m_DecayTime); } } return 0; } /// /// Change the envelope so that it stops at a specific offset from its start time. /// Use this to extend or cut short an existing envelope, while respecting the /// attack and decay as much as possible. /// /// When to stop the envelope /// If true, enevlope will not decay, but cut off instantly public void ChangeStopTime(float offset, bool forceNoDecay) { if (offset < 0) offset = 0; if (offset < m_AttackTime) m_AttackTime = 0; // How to prevent pop? GML m_SustainTime = offset - m_AttackTime; if (forceNoDecay) m_DecayTime = 0; } /// /// Set the envelop times to 0 and the shapes to default. /// public void Clear() { m_AttackShape = m_DecayShape = null; m_AttackTime = m_SustainTime = m_DecayTime = 0; } /// /// Call from OnValidate to ensure that envelope values are sane /// public void Validate() { m_AttackTime = Mathf.Max(0, m_AttackTime); m_DecayTime = Mathf.Max(0, m_DecayTime); m_SustainTime = Mathf.Max(0, m_SustainTime); } } internal static float EvaluateDissipationScale(float spread, float normalizedDistance) { const float kMin = -0.8f; const float kMax = 0.8f; var b = kMin + (kMax - kMin) * (1f - spread); b = (1f - b) * 0.5f; var t = Mathf.Clamp01(normalizedDistance) / ((((1f/Mathf.Clamp01(b)) - 2f) * (1f - normalizedDistance)) + 1f); return 1 - SplineHelpers.Bezier1(t, 0, 0, 1, 1); } /// Describes an event that generates an impulse signal on one or more channels. /// The event has a location in space, a start time, a duration, and a signal. The signal /// will dissipate as the distance from the event location increases. public class ImpulseEvent { /// Start time of the event. public float m_StartTime; /// Time-envelope of the signal. public EnvelopeDefinition m_Envelope; /// Raw signal source. The ouput of this will be scaled to fit in the envelope. public ISignalSource6D m_SignalSource; /// Worldspace origin of the signal. public Vector3 m_Position; /// Radius around the signal origin that has full signal value. Distance dissipation begins after this distance. public float m_Radius; /// How the signal behaves as the listener moves away from the origin. public enum DirectionMode { /// Signal direction remains constant everywhere. Fixed, /// Signal is rotated in the direction of the source. RotateTowardSource } /// How the signal direction behaves as the listener moves away from the source. public DirectionMode m_DirectionMode = DirectionMode.Fixed; /// Channels on which this event will broadcast its signal. public int m_Channel; /// How the signal dissipates with distance. public enum DissipationMode { /// Simple linear interpolation to zero over the dissipation distance. LinearDecay, /// Ease-in-ease-out dissipation over the dissipation distance. SoftDecay, /// Half-life decay, hard out from full and ease into 0 over the dissipation distance. ExponentialDecay } /// How the signal dissipates with distance. public DissipationMode m_DissipationMode; /// Distance over which the dissipation occurs. Must be >= 0. public float m_DissipationDistance; /// /// How the effect fades with distance. 0 = no dissipation, 1 = rapid dissipation, -1 = off (legacy mode) /// public float m_CustomDissipation; /// /// The speed (m/s) at which the impulse propagates through space. High speeds /// allow listeners to react instantaneously, while slower speeds allow listeres in the /// scene to react as if to a wave spreading from the source. /// public float m_PropagationSpeed; /// Returns true if the event is no longer generating a signal because its time has expired public bool Expired { get { var d = m_Envelope.Duration; var maxDistance = m_Radius + m_DissipationDistance; float time = Instance.CurrentTime - maxDistance / Mathf.Max(1, m_PropagationSpeed); return d > 0 && m_StartTime + d <= time; } } /// Cancel the event at the supplied time /// The time at which to cancel the event /// If true, event will be cut immediately at the time, /// otherwise its envelope's decay curve will begin at the cancel time public void Cancel(float time, bool forceNoDecay) { m_Envelope.m_HoldForever = false; m_Envelope.ChangeStopTime(time - m_StartTime, forceNoDecay); } /// Calculate the the decay applicable at a given distance from the impact point /// The distance over which to perform the decay /// Scale factor 0...1 public float DistanceDecay(float distance) { float radius = Mathf.Max(m_Radius, 0); if (distance < radius) return 1; distance -= radius; if (distance >= m_DissipationDistance) return 0; if (m_CustomDissipation >= 0) return EvaluateDissipationScale(m_CustomDissipation, distance / m_DissipationDistance); switch (m_DissipationMode) { default: case DissipationMode.LinearDecay: return Mathf.Lerp(1, 0, distance / m_DissipationDistance); case DissipationMode.SoftDecay: return 0.5f * (1 + Mathf.Cos(Mathf.PI * (distance / m_DissipationDistance))); case DissipationMode.ExponentialDecay: return 1 - Damper.Damp(1, m_DissipationDistance, distance); } } /// Get the signal that a listener at a given position would perceive /// The listener's position in world space /// True if distance calculation should ignore Z /// The position impulse signal /// The rotation impulse signal /// true if non-trivial signal is returned public bool GetDecayedSignal( Vector3 listenerPosition, bool use2D, out Vector3 pos, out Quaternion rot) { if (m_SignalSource != null) { float distance = use2D ? Vector2.Distance(listenerPosition, m_Position) : Vector3.Distance(listenerPosition, m_Position); float time = Instance.CurrentTime - m_StartTime - distance / Mathf.Max(1, m_PropagationSpeed); float scale = m_Envelope.GetValueAt(time) * DistanceDecay(distance); if (scale != 0) { m_SignalSource.GetSignal(time, out pos, out rot); pos *= scale; rot = Quaternion.SlerpUnclamped(Quaternion.identity, rot, scale); if (m_DirectionMode == DirectionMode.RotateTowardSource && distance > Epsilon) { Quaternion q = Quaternion.FromToRotation(Vector3.up, listenerPosition - m_Position); if (m_Radius > Epsilon) { float t = Mathf.Clamp01(distance / m_Radius); q = Quaternion.Slerp( q, Quaternion.identity, Mathf.Cos(Mathf.PI * t / 2)); } pos = q * pos; } return true; } } pos = Vector3.zero; rot = Quaternion.identity; return false; } /// Reset the event to a default state public void Clear() { m_Envelope.Clear(); m_StartTime = 0; m_SignalSource = null; m_Position = Vector3.zero; m_Channel = 0; m_Radius = 0; m_DissipationDistance = 100; m_DissipationMode = DissipationMode.ExponentialDecay; m_CustomDissipation = -1; } /// Don't create them yourself. Use CinemachineImpulseManager.NewImpulseEvent(). internal ImpulseEvent() {} } List m_ExpiredEvents; List m_ActiveEvents; /// Get the signal perceived by a listener at a geven location /// Where the listener is, in world coords /// True if distance calculation should ignore Z /// Only Impulse signals on channels in this mask will be considered /// The combined position impulse signal resulting from all signals active on the specified channels /// The combined rotation impulse signal resulting from all signals active on the specified channels /// true if non-trivial signal is returned public bool GetImpulseAt( Vector3 listenerLocation, bool distance2D, int channelMask, out Vector3 pos, out Quaternion rot) { bool nontrivialResult = false; pos = Vector3.zero; rot = Quaternion.identity; if (m_ActiveEvents != null) { for (int i = m_ActiveEvents.Count - 1; i >= 0; --i) { ImpulseEvent e = m_ActiveEvents[i]; // Prune invalid or expired events if (e == null || e.Expired) { m_ActiveEvents.RemoveAt(i); if (e != null) { // Recycle it if (m_ExpiredEvents == null) m_ExpiredEvents = new List(); e.Clear(); m_ExpiredEvents.Add(e); } } else if ((e.m_Channel & channelMask) != 0) { Vector3 pos0 = Vector3.zero; Quaternion rot0 = Quaternion.identity; if (e.GetDecayedSignal(listenerLocation, distance2D, out pos0, out rot0)) { nontrivialResult = true; pos += pos0; rot *= rot0; } } } } return nontrivialResult; } /// Set this to ignore time scaling so impulses can progress while the game is paused public bool IgnoreTimeScale; /// /// This is the Impulse system's current time. /// Takes into accoount whether impulse is ignoring time scale. /// public float CurrentTime => IgnoreTimeScale ? Time.realtimeSinceStartup : CinemachineCore.CurrentTime; /// Get a new ImpulseEvent /// A newly-created impulse event. May be recycled from expired events public ImpulseEvent NewImpulseEvent() { ImpulseEvent e; if (m_ExpiredEvents == null || m_ExpiredEvents.Count == 0) return new ImpulseEvent() { m_CustomDissipation = -1 }; e = m_ExpiredEvents[m_ExpiredEvents.Count-1]; m_ExpiredEvents.RemoveAt(m_ExpiredEvents.Count-1); return e; } /// Activate an impulse event, so that it may begin broadcasting its signal /// Events will be automatically removed after they expire. /// You can tweak the ImpulseEvent fields dynamically if you keep a pointer to it. /// The event to add to the current active events public void AddImpulseEvent(ImpulseEvent e) { if (m_ActiveEvents == null) m_ActiveEvents = new List(); if (e != null) { e.m_StartTime = CurrentTime; m_ActiveEvents.Add(e); } } /// Immediately terminate all active impulse signals public void Clear() { if (m_ActiveEvents != null) { for (int i = 0; i < m_ActiveEvents.Count; ++i) m_ActiveEvents[i].Clear(); m_ActiveEvents.Clear(); } } } }