Files
GameDevTVObstacleDodge/Library/PackageCache/com.unity.cinemachine@5342685532bb/Runtime/Impulse/CinemachineImpulseManager.cs

491 lines
22 KiB
C#
Raw Normal View History

2026-01-08 16:50:20 +00:00
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
namespace Unity.Cinemachine
{
/// <summary>
/// Property applied to CinemachineImpulseManager Channels.
/// Used for custom drawing in the inspector.
/// </summary>
public sealed class CinemachineImpulseChannelPropertyAttribute : PropertyAttribute {}
/// <summary>
/// This is a singleton object that manages all Impulse Events generated by the Cinemachine
/// Impulse module. This singleton owns and manages all ImpulseEvent objects.
/// </summary>
public class CinemachineImpulseManager
{
private CinemachineImpulseManager() {}
private static CinemachineImpulseManager s_Instance = null;
/// <summary>Get the singleton instance</summary>
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;
/// <summary>This defines the time-envelope of the signal.
/// The raw signal will be scaled to fit inside the envelope.</summary>
[Serializable]
public struct EnvelopeDefinition
{
/// <summary>Normalized curve defining the shape of the start of the envelope.</summary>
[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;
/// <summary>Normalized curve defining the shape of the end of the envelope.</summary>
[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;
/// <summary>Duration in seconds of the attack. Attack curve will be scaled to fit. Must be >= 0</summary>
[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
/// <summary>Duration in seconds of the central fully-scaled part of the envelope. Must be >= 0.</summary>
[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
/// <summary>Duration in seconds of the decay. Decay curve will be scaled to fit. Must be >= 0.</summary>
[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
/// <summary>If checked, signal amplitude scaling will also be applied to the time
/// envelope of the signal. Bigger signals will last longer</summary>
[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;
/// <summary>If true, then duration is infinite.</summary>
[Tooltip("If true, then duration is infinite.")]
[FormerlySerializedAs("m_HoldForever")]
public bool HoldForever;
/// <summary>An envelope with default values.</summary>
public static EnvelopeDefinition Default => new() { DecayTime = 0.7f, SustainTime = 0.2f, ScaleWithImpact = true };
/// <summary>Duration of the envelope, in seconds. If negative, then duration is infinite.</summary>
public readonly float Duration => HoldForever ? -1 : AttackTime + SustainTime + DecayTime;
/// <summary>
/// Get the value of the envelope at a given time relative to the envelope start.
/// </summary>
/// <param name="offset">Time in seconds from the envelope start</param>
/// <returns>Envelope amplitude. This will range from 0...1</returns>
public readonly 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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="offset">When to stop the envelope</param>
/// <param name="forceNoDecay">If true, envelope will not decay, but cut off instantly</param>
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;
}
/// <summary>
/// Set the envelop times to 0 and the shapes to default.
/// </summary>
public void Clear()
{
AttackShape = DecayShape = null;
AttackTime = SustainTime = DecayTime = 0;
}
/// <summary>
/// Call from OnValidate to ensure that envelope values are sane
/// </summary>
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);
}
/// <summary>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.</summary>
public class ImpulseEvent
{
/// <summary>Start time of the event.</summary>
public float StartTime;
/// <summary>Time-envelope of the signal.</summary>
public EnvelopeDefinition Envelope;
/// <summary>Raw signal source. The output of this will be scaled to fit in the envelope.</summary>
public ISignalSource6D SignalSource;
/// <summary>World-space origin of the signal.</summary>
public Vector3 Position;
/// <summary>Radius around the signal origin that has full signal value. Distance dissipation begins after this distance.</summary>
public float Radius;
/// <summary>How the signal behaves as the listener moves away from the origin.</summary>
public enum DirectionModes
{
/// <summary>Signal direction remains constant everywhere.</summary>
Fixed,
/// <summary>Signal is rotated in the direction of the source.</summary>
RotateTowardSource
}
/// <summary>How the signal direction behaves as the listener moves away from the source.</summary>
public DirectionModes DirectionMode = DirectionModes.Fixed;
/// <summary>Channels on which this event will broadcast its signal.</summary>
public int Channel;
/// <summary>How the signal dissipates with distance.</summary>
public enum DissipationModes
{
/// <summary>Simple linear interpolation to zero over the dissipation distance.</summary>
LinearDecay,
/// <summary>Ease-in-ease-out dissipation over the dissipation distance.</summary>
SoftDecay,
/// <summary>Half-life decay, hard out from full and ease into 0 over the dissipation distance.</summary>
ExponentialDecay
}
/// <summary>How the signal dissipates with distance.</summary>
public DissipationModes DissipationMode;
/// <summary>Distance over which the dissipation occurs. Must be >= 0.</summary>
public float DissipationDistance;
/// <summary>
/// How the effect fades with distance. 0 = no dissipation, 1 = rapid dissipation, -1 = off (legacy mode)
/// </summary>
public float CustomDissipation;
/// <summary>
/// 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.
/// </summary>
public float PropagationSpeed;
/// <summary>Returns true if the event is no longer generating a signal because its time has expired</summary>
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;
}
}
/// <summary>Cancel the event at the supplied time</summary>
/// <param name="time">The time at which to cancel the event</param>
/// <param name="forceNoDecay">If true, event will be cut immediately at the time,
/// otherwise its envelope's decay curve will begin at the cancel time</param>
public void Cancel(float time, bool forceNoDecay)
{
Envelope.HoldForever = false;
Envelope.ChangeStopTime(time - StartTime, forceNoDecay);
}
/// <summary>Calculate the the decay applicable at a given distance from the impact point</summary>
/// <param name="distance">The distance over which to perform the decay</param>
/// <returns>Scale factor 0...1</returns>
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);
}
}
/// <summary>Get the signal that a listener at a given position would perceive</summary>
/// <param name="listenerPosition">The listener's position in world space</param>
/// <param name="use2D">True if distance calculation should ignore Z</param>
/// <param name="pos">The position impulse signal</param>
/// <param name="rot">The rotation impulse signal</param>
/// <returns>true if non-trivial signal is returned</returns>
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;
}
/// <summary>Reset the event to a default state</summary>
public void Clear()
{
Envelope.Clear();
StartTime = 0;
SignalSource = null;
Position = Vector3.zero;
Channel = 0;
Radius = 0;
DissipationDistance = 100;
DissipationMode = DissipationModes.ExponentialDecay;
CustomDissipation = -1;
}
/// <summary>Don't create them yourself. Use CinemachineImpulseManager.NewImpulseEvent().</summary>
internal ImpulseEvent() {}
}
List<ImpulseEvent> m_ExpiredEvents;
List<ImpulseEvent> m_ActiveEvents;
/// <summary>Get the signal perceived by a listener at a given location. The effects from all
/// contributing signals are combined together.</summary>
/// <param name="listenerLocation">Where the listener is, in world coords.</param>
/// <param name="distance2D">True if distance calculation should ignore Z.</param>
/// <param name="channelMask">Only Impulse signals on channels in this mask will be considered.</param>
/// <param name="pos">The combined position impulse signal resulting from all signals active on the specified channels.</param>
/// <param name="rot">The combined rotation impulse signal resulting from all signals active on the specified channels.</param>
/// <returns>true if non-trivial signal is returned.</returns>
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)
{
var e = m_ActiveEvents[i];
if (e == null || e.Expired)
{
// Prune invalid or expired events
m_ActiveEvents.RemoveAt(i);
if (e != null)
{
// Recycle it
m_ExpiredEvents ??= new ();
e.Clear();
m_ExpiredEvents.Add(e);
}
}
else if ((e.Channel & channelMask) != 0)
{
if (e.GetDecayedSignal(listenerLocation, distance2D, out var pos0, out var rot0))
{
nontrivialResult = true;
pos += pos0;
rot *= rot0;
}
}
}
}
return nontrivialResult;
}
/// <summary>Get the signal perceived by a listener at a given location.
/// Only the signal with the greatest amplitude is considered, all others are ignored.</summary>
/// <param name="listenerLocation">Where the listener is, in world coords.</param>
/// <param name="distance2D">True if distance calculation should ignore Z.</param>
/// <param name="channelMask">Only Impulse signals on channels in this mask are considered.</param>
/// <param name="pos">The combined position impulse signal resulting from all signals active on the specified channels.</param>
/// <param name="rot">The combined rotation impulse signal resulting from all signals active on the specified channels.</param>
/// <returns>true if non-trivial signal is returned.</returns>
public bool GetStrongestImpulseAt(
Vector3 listenerLocation, bool distance2D, int channelMask,
out Vector3 pos, out Quaternion rot)
{
bool nontrivialResult = false;
var strongestPos = Vector3.zero;
var strongestRot = Quaternion.identity;
if (m_ActiveEvents != null)
{
float strongestPosMagnitude = 0f;
for (int i = m_ActiveEvents.Count - 1; i >= 0; --i)
{
var e = m_ActiveEvents[i];
if (e == null || e.Expired)
{
// Prune invalid or expired events
m_ActiveEvents.RemoveAt(i);
if (e != null)
{
// Recycle it
m_ExpiredEvents ??= new ();
e.Clear();
m_ExpiredEvents.Add(e);
}
}
else if ((e.Channel & channelMask) != 0)
{
if (e.GetDecayedSignal(listenerLocation, distance2D, out var pos0, out var rot0))
{
nontrivialResult = true;
float posMagnitude = pos0.sqrMagnitude;
if (posMagnitude > strongestPosMagnitude)
{
strongestPosMagnitude = posMagnitude;
strongestPos = pos0;
strongestRot = rot0;
}
}
}
}
}
pos = strongestPos;
rot = strongestRot;
return nontrivialResult;
}
/// <summary>Set this to ignore time scaling so impulses can progress while the game is paused</summary>
public bool IgnoreTimeScale;
/// <summary>
/// This is the Impulse system's current time.
/// Takes into account whether impulse is ignoring time scale.
/// </summary>
public float CurrentTime => IgnoreTimeScale ? Time.realtimeSinceStartup : CinemachineCore.CurrentTime;
/// <summary>Get a new ImpulseEvent</summary>
/// <returns>A newly-created impulse event. May be recycled from expired events</returns>
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;
}
/// <summary>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.</summary>
/// <param name="e">The event to add to the current active events</param>
public void AddImpulseEvent(ImpulseEvent e)
{
if (m_ActiveEvents == null)
m_ActiveEvents = new List<ImpulseEvent>();
if (e != null)
{
e.StartTime = CurrentTime;
m_ActiveEvents.Add(e);
}
}
/// <summary>Immediately terminate all active impulse signals</summary>
public void Clear()
{
if (m_ActiveEvents != null)
{
for (int i = 0; i < m_ActiveEvents.Count; ++i)
m_ActiveEvents[i].Clear();
m_ActiveEvents.Clear();
}
}
}
}