using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
namespace Unity.Cinemachine
{
///
/// 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 objects.
///
public class CinemachineImpulseManager
{
private CinemachineImpulseManager() {}
private static CinemachineImpulseManager s_Instance = null;
/// Get the singleton instance
public static CinemachineImpulseManager Instance
{
get
{
if (s_Instance == null)
s_Instance = new CinemachineImpulseManager();
return s_Instance;
}
}
[RuntimeInitializeOnLoadMethod]
static void InitializeModule()
{
if (s_Instance != null)
s_Instance.Clear();
}
const float Epsilon = UnityVectorExtensions.Epsilon;
/// This defines the time-envelope of the signal.
/// The 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")]
[FormerlySerializedAs("m_AttackShape")]
public AnimationCurve 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")]
[FormerlySerializedAs("m_DecayShape")]
public AnimationCurve 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.")]
[FormerlySerializedAs("m_AttackTime")]
public float 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.")]
[FormerlySerializedAs("m_SustainTime")]
public float 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.")]
[FormerlySerializedAs("m_DecayTime")]
public float 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.")]
[FormerlySerializedAs("m_ScaleWithImpact")]
public bool ScaleWithImpact;
/// If true, then duration is infinite.
[Tooltip("If true, then duration is infinite.")]
[FormerlySerializedAs("m_HoldForever")]
public bool HoldForever;
/// Get an envelope with default values.
/// An event with default values
public static EnvelopeDefinition Default => new() { DecayTime = 0.7f, SustainTime = 0.2f, ScaleWithImpact = true };
/// Duration of the envelope, in seconds. If negative, then duration is infinite.
public float Duration => HoldForever ? -1 : AttackTime + SustainTime + DecayTime;
///
/// Get the value of the envelope 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 < AttackTime && AttackTime > Epsilon)
{
if (AttackShape == null || AttackShape.length < 2)
return Damper.Damp(1, AttackTime, offset);
return AttackShape.Evaluate(offset / AttackTime);
}
offset -= AttackTime;
if (HoldForever || offset < SustainTime)
return 1;
offset -= SustainTime;
if (offset < DecayTime && DecayTime > Epsilon)
{
if (DecayShape == null || DecayShape.length < 2)
return 1 - Damper.Damp(1, DecayTime, offset);
return DecayShape.Evaluate(offset / 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, envelope will not decay, but cut off instantly
public void ChangeStopTime(float offset, bool forceNoDecay)
{
if (offset < 0)
offset = 0;
if (offset < AttackTime)
AttackTime = 0; // How to prevent pop? GML
SustainTime = offset - AttackTime;
if (forceNoDecay)
DecayTime = 0;
}
///
/// Set the envelop times to 0 and the shapes to default.
///
public void Clear()
{
AttackShape = DecayShape = null;
AttackTime = SustainTime = DecayTime = 0;
}
///
/// Call from OnValidate to ensure that envelope values are sane
///
public void Validate()
{
AttackTime = Mathf.Max(0, AttackTime);
DecayTime = Mathf.Max(0, DecayTime);
SustainTime = Mathf.Max(0, 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 StartTime;
/// Time-envelope of the signal.
public EnvelopeDefinition Envelope;
/// Raw signal source. The output of this will be scaled to fit in the envelope.
public ISignalSource6D SignalSource;
/// World-space origin of the signal.
public Vector3 Position;
/// Radius around the signal origin that has full signal value. Distance dissipation begins after this distance.
public float Radius;
/// How the signal behaves as the listener moves away from the origin.
public enum DirectionModes
{
/// 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 DirectionModes DirectionMode = DirectionModes.Fixed;
/// Channels on which this event will broadcast its signal.
public int Channel;
/// How the signal dissipates with distance.
public enum DissipationModes
{
/// 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 DissipationModes DissipationMode;
/// Distance over which the dissipation occurs. Must be >= 0.
public float DissipationDistance;
///
/// How the effect fades with distance. 0 = no dissipation, 1 = rapid dissipation, -1 = off (legacy mode)
///
public float CustomDissipation;
///
/// The speed (m/s) at which the impulse propagates through space. High speeds
/// allow listeners to react instantaneously, while slower speeds allow listeners in the
/// scene to react as if to a wave spreading from the source.
///
public float PropagationSpeed;
/// Returns true if the event is no longer generating a signal because its time has expired
public bool Expired
{
get
{
var d = Envelope.Duration;
var maxDistance = Radius + DissipationDistance;
float time = Instance.CurrentTime - maxDistance / Mathf.Max(1, PropagationSpeed);
return d > 0 && 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)
{
Envelope.HoldForever = false;
Envelope.ChangeStopTime(time - 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(Radius, 0);
if (distance < radius)
return 1;
distance -= radius;
if (distance >= DissipationDistance)
return 0;
if (CustomDissipation >= 0)
return EvaluateDissipationScale(CustomDissipation, distance / DissipationDistance);
switch (DissipationMode)
{
default:
case DissipationModes.LinearDecay:
return Mathf.Lerp(1, 0, distance / DissipationDistance);
case DissipationModes.SoftDecay:
return 0.5f * (1 + Mathf.Cos(Mathf.PI * (distance / DissipationDistance)));
case DissipationModes.ExponentialDecay:
return 1 - Damper.Damp(1, 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 (SignalSource != null)
{
float distance = use2D ? Vector2.Distance(listenerPosition, Position)
: Vector3.Distance(listenerPosition, Position);
float time = Instance.CurrentTime - StartTime
- distance / Mathf.Max(1, PropagationSpeed);
float scale = Envelope.GetValueAt(time) * DistanceDecay(distance);
if (scale != 0)
{
SignalSource.GetSignal(time, out pos, out rot);
pos *= scale;
rot = Quaternion.SlerpUnclamped(Quaternion.identity, rot, scale);
if (DirectionMode == DirectionModes.RotateTowardSource && distance > Epsilon)
{
Quaternion q = Quaternion.FromToRotation(Vector3.up, listenerPosition - Position);
if (Radius > Epsilon)
{
float t = Mathf.Clamp01(distance / 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()
{
Envelope.Clear();
StartTime = 0;
SignalSource = null;
Position = Vector3.zero;
Channel = 0;
Radius = 0;
DissipationDistance = 100;
DissipationMode = DissipationModes.ExponentialDecay;
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 given 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.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 account 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() { 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.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();
}
}
}
}