Player component that builds the 'patchwork': grows one Graft per healed misfit, ordered as they were first grafted, and shows each with a short ceremony (sound, notice line, calm restored). It is the single place graft passives are applied, summing speed, gravity, jump, grip, phobia resistance, landing cushion, stillness calm and scouting pings each frame, and it also routes ability key presses to slots 1 to 9, manages the unseen/toy/ghost states, and draws and fades the ping beacons.
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The grafts the player has grown from healed misfits: over a run the lizard becomes a patchwork
/// of everyone it has helped. Sits on the player (the bootstrap adds it). It grows a
/// <see cref="Graft"/> for every misfit already healed, and a new one, with a little ceremony,
/// each time <see cref="SumpState.MisfitHealed"/> fires.
///
/// This is also the ONE place the grafts' passive effects are applied. Every frame it adds up the
/// <see cref="GraftPassive"/> of every active graft and writes the totals: speed through the
/// controller's named speed factors ("graft_<misfit index>", one per graft), gravity, jump
/// and grip as multiples of the values it found (put back exactly when the grafts go), the
/// phobia's resistance as an added share, plus the landing cushion, the calm while still and the
/// scouting ping. Nothing else writes those on the grafts' behalf, so any number combine.
///
/// Keys: the Nth graft's ability is on the input action "SlotN" (keys 1 to 9), in the order grafted.
///
/// For other modules:
/// tag "sump_unseen" on the player object, <see cref="Unseen"/>, <see cref="HiddenFrom"/> -
/// the player cannot be seen or grabbed (Unwatched, Toy stillness);
/// tag "sump_priced" on a frozen human or object (Price tag); see <see cref="PriceTagGraft"/>;
/// <see cref="MagnetPoint"/> - where thrown and fired things should go instead of at the player;
/// <see cref="SetActive"/> - flashbacks switch every graft off and on again.
/// </summary>
[Title( "Patchwork" ), Category( "Sump" ), Icon( "healing" )]
public sealed class Patchwork : Component
{
/// <summary>On the player object while nobody can notice the player.</summary>
public const string UnseenTag = "sump_unseen";
/// <summary>On a human or object frozen by a price tag.</summary>
public const string PricedTag = "sump_priced";
/// <summary>While set, loose, thrown and fired things should head here instead of at the player.</summary>
public static Vector3? MagnetPoint { get; set; }
/// <summary>How far from <see cref="MagnetPoint"/> it reaches, in inches.</summary>
public static float MagnetRadius { get; set; } = 650f;
// ---- Tuning: the ceremony -----------------------------------------------------------------
/// <summary>Seconds after a misfit is healed before its graft starts to swell out (the flashback is still fading).</summary>
[Property, Group( "Ceremony" )] public float CeremonyDelay { get; set; } = 1.5f;
/// <summary>Calm given back as a graft grows in (1 is a full meter).</summary>
[Property, Group( "Ceremony" ), Range( 0f, 1f )] public float SootheOnGraft { get; set; } = 0.35f;
/// <summary>Seconds a <see cref="Notice"/> stays up.</summary>
[Property, Group( "Ceremony" )] public float NoticeSeconds { get; set; } = 8f;
// ---- Tuning: the passives -----------------------------------------------------------------
/// <summary>However many gas sacs, gravity never drops below this share of normal.</summary>
[Property, Group( "Passives" )] public float MinGravity { get; set; } = 0.4f;
/// <summary>However many grafts, one of them never changes speed by more than this factor either way.</summary>
[Property, Group( "Passives" )] public float MaxSpeedFactor { get; set; } = 1.6f;
/// <summary>However many jellies, grip never reaches further than this multiple of normal.</summary>
[Property, Group( "Passives" )] public float MaxGrip { get; set; } = 1.6f;
/// <summary>The lizard counts as on a wall or ceiling when its up leans this far over (z of the surface normal).</summary>
[Property, Group( "Passives" ), Range( 0f, 1f )] public float WallUpZ { get; set; } = 0.7f;
/// <summary>Machine: seconds of running straight to reach the full boost.</summary>
[Property, Group( "Passives" )] public float StraightSeconds { get; set; } = 1.4f;
/// <summary>Machine: turning faster than this (degrees per second) loses the boost.</summary>
[Property, Group( "Passives" )] public float StraightTurnLimit { get; set; } = 70f;
/// <summary>Jelly: falls faster than this are braked just above the ground, in inches per second.</summary>
[Property, Group( "Passives" )] public float CushionSpeed { get; set; } = 320f;
/// <summary>Fungus: slower than this counts as keeping still, in inches per second.</summary>
[Property, Group( "Passives" )] public float StillSpeed { get; set; } = 25f;
/// <summary>Swarm: unhealed misfits within this are shown by a ping, in inches.</summary>
[Property, Group( "Passives" )] public float PingRange { get; set; } = 7000f;
/// <summary>Swarm: seconds a ping's beacons stay up.</summary>
[Property, Group( "Passives" )] public float PingSeconds { get; set; } = 3.5f;
// ---- Tuning: abilities --------------------------------------------------------------------
/// <summary>Unwatched: someone facing the player more squarely than this (cosine) still sees it.</summary>
[Property, Group( "Abilities" ), Range( -1f, 1f )] public float WatchingDot { get; set; } = 0.5f;
/// <summary>Unwatched: how dark the lizard's body is tinted while it lasts (0 black, 1 unchanged).</summary>
[Property, Group( "Abilities" ), Range( 0f, 1f )] public float GhostTint { get; set; } = 0.3f;
// ---- Read by the HUD and other modules ----------------------------------------------------
/// <summary>The player's patchwork, or null.</summary>
public static Patchwork Of( ReptileController player ) => player.IsValid() ? player.Components.Get<Patchwork>() : null;
/// <summary>Every graft, in the order grafted (the Nth is on key N).</summary>
public IReadOnlyList<IGraft> Grafts => _grafts;
public bool Has( BodyPlan plan ) => _grafts.Any( g => g.IsValid() && g.Plan == plan );
public bool Has( TwistedAbility ability ) => _grafts.Any( g => g.IsValid() && g.Source is not null && g.Source.Ability == ability );
/// <summary>False while grafts are switched off (a flashback).</summary>
public bool GraftsActive => _activeAll;
public ReptileController Player => _player;
/// <summary>True while nobody can notice the player (Unwatched or Toy stillness). The tag "sump_unseen" says the same.</summary>
public bool Unseen => _unwatchedBy.Count > 0 || _toyUnseenBy.Count > 0;
/// <summary>True while the player is a toy: unseen by everyone, whichever way they face.</summary>
public bool IsToy => _toyUnseenBy.Count > 0;
/// <summary>How big the lizard's body is against normal (below 1 while a toy). Grafts shrink with it.</summary>
public float BodyScale { get; private set; } = 1f;
/// <summary>The newest thing worth telling the player (a new graft and what it does, why an ability refused), or empty.</summary>
public string Notice => RealTime.Now < _noticeUntil ? _notice : "";
/// <summary>Where the last scouting ping found unhealed misfits.</summary>
public IReadOnlyList<Vector3> LastPing => _lastPing;
/// <summary>
/// Can somebody with their eyes here, facing this way, NOT notice the player right now?
/// A toy is hidden from everyone; the unwatched are hidden from whoever is not facing them.
/// Humans, misfits and the finale's cells should ask this before they see or grab the player.
/// </summary>
public static bool HiddenFrom( Vector3 eye, Vector3 facing )
{
var patchwork = Of( Sump.Player );
if ( !patchwork.IsValid() || !patchwork.Unseen ) return false;
if ( patchwork.IsToy ) return true;
var to = patchwork.WorldPosition - eye;
if ( to.Length < 1f ) return false;
return Vector3.Dot( facing.Normal, to.Normal ) < patchwork.WatchingDot;
}
/// <summary>Everything grown, one graft per line, for a HUD panel.</summary>
public string Summary
{
get
{
if ( _grafts.Count == 0 ) return "";
var lines = new List<string> { _activeAll ? $"PATCHWORK ({_grafts.Count})" : "PATCHWORK (asleep)" };
foreach ( var graft in _grafts )
{
if ( !graft.IsValid() ) continue;
lines.Add( $"{graft.Name}'s {graft.Entry.PartName} - {graft.Entry.PassiveLine}" );
var ability = graft.Ability;
if ( ability.IsValid() )
{
string key = graft.Slot <= 9 ? $"[{graft.Slot}]" : "[-]";
string status = !graft.On ? "off" : graft.Grown01 < 1f ? "growing" : ability.Status;
lines.Add( $" {key} {ability.Title}: {status}" );
}
}
return string.Join( '\n', lines );
}
}
/// <summary>
/// Switches every graft off or on. Off, the parts are hidden, the abilities are undone and the
/// passive changes to the controller and the phobia are put back exactly. Flashbacks call this:
/// the player relives memories without them.
/// </summary>
public void SetActive( bool active )
{
_activeAll = active;
foreach ( var graft in _grafts )
if ( graft.IsValid() ) graft.On = active;
if ( !active ) LetGo();
}
// ---- For the grafts and their abilities ---------------------------------------------------
/// <summary>Puts a line up for the HUD (<see cref="Notice"/>).</summary>
public void Note( string text )
{
_notice = text ?? "";
_noticeUntil = RealTime.Now + NoticeSeconds;
}
/// <summary>An ability hides the player (toy = from everyone) or stops hiding it.</summary>
public void SetUnseen( object by, bool toy, bool on )
{
var set = toy ? _toyUnseenBy : _unwatchedBy;
if ( on ) set.Add( by ); else set.Remove( by );
ApplyUnseenTag();
}
/// <summary>An ability shrinks the lizard's body to this share of its size (1 gives it back).</summary>
public void SetToy( object by, float scale )
{
if ( scale >= 0.999f ) _toyBy.Remove( by );
else _toyBy[by] = Math.Clamp( scale, 0.05f, 1f );
ApplyBodyScale();
}
/// <summary>An ability darkens the lizard's body to a ghost of itself, or gives its colours back.</summary>
public void SetGhost( object by, bool on )
{
bool was = _ghostBy.Count > 0;
if ( on ) _ghostBy.Add( by ); else _ghostBy.Remove( by );
bool now = _ghostBy.Count > 0;
if ( now && !was ) GhostOn();
else if ( !now && was ) GhostOff();
}
/// <summary>Where the camera is and which way it looks. False if there is no camera.</summary>
public bool AimRay( out Vector3 eye, out Vector3 forward )
{
var camera = Scene.Camera;
if ( !camera.IsValid() )
{
eye = WorldPosition + Vector3.Up * 30f;
forward = WorldRotation.Forward;
return false;
}
eye = camera.WorldPosition;
forward = camera.WorldRotation.Forward;
return true;
}
/// <summary>
/// The spot under the middle of the screen, no further than range from the lizard, with what
/// was hit there (null for open air) and the surface's normal (up for open air).
/// </summary>
public Vector3 AimPoint( float range, out GameObject hit, out Vector3 normal )
{
AimRay( out var eye, out var forward );
// The camera hangs behind the lizard, so the ray is that much longer.
float behind = _player.IsValid() ? (eye - _player.WorldPosition).Length : 0f;
var end = eye + forward * (range + behind);
var trace = Scene.Trace.Ray( eye, end ).IgnoreGameObjectHierarchy( GameObject ).Run();
hit = trace.Hit ? trace.GameObject : null;
normal = trace.Hit ? trace.Normal : Vector3.Up;
return trace.Hit ? trace.HitPosition : end;
}
/// <summary>Called by a graft as it starts to swell out: the ceremony.</summary>
public void GraftSwelling( Graft graft )
{
if ( !graft.IsValid() ) return;
Sump.Sfx( "graft_squelch", graft.PartPosition );
if ( _player.IsValid() ) _player.Kick( Vector3.Down * 5f );
// The lizard's own inner voice (no speaker name), then what it can do now.
Sump.Say( "", string.Format( graft.Entry.VoiceLine, graft.Name ), 6f );
string text = $"New graft: {graft.Name}'s {graft.Entry.PartName} - {graft.Entry.PassiveLine}.";
if ( graft.Ability.IsValid() )
text += graft.Slot <= 9
? $" {graft.Slot} {graft.Ability.Title} ({graft.Ability.HowTo})"
: $" {graft.Ability.Title} has no key left.";
Note( text );
var phobia = Phobia();
if ( phobia.IsValid() ) phobia.Soothe( SootheOnGraft );
}
// ---- State --------------------------------------------------------------------------------
const string OrderNote = "grafts.order";
readonly List<Graft> _grafts = new();
ReptileController _player;
PlayerPhobia _phobia;
bool _activeAll = true, _started;
float _nextSync;
string _notice = "";
float _noticeUntil;
readonly HashSet<object> _unwatchedBy = new();
readonly HashSet<object> _toyUnseenBy = new();
readonly HashSet<object> _ghostBy = new();
readonly Dictionary<object, float> _toyBy = new();
bool _tagged;
// What we changed on the controller, each remembered so it can be put back exactly.
readonly Share _gravity = new();
readonly Share _jump = new();
readonly Share _stick = new();
readonly Share _reach = new();
readonly HashSet<string> _speedNames = new();
float _resistanceGiven, _resistanceWritten;
bool _resistanceOn;
// The body's own scale and colours, as they were before a toy or a ghost.
Vector3 _bodyScaleWas;
bool _bodyScaled;
readonly List<(ModelRenderer Renderer, Color Was)> _ghosted = new();
// Machine: how straight the run has been, 0 to 1.
float _straight;
Vector3 _lastHeading;
// Swarm: the beacons of the last ping.
TimeSince _sincePing = 5f;
readonly List<(GameObject Go, float Born)> _beacons = new();
readonly List<Vector3> _lastPing = new();
PlayerPhobia Phobia()
{
if ( !_phobia.IsValid() ) _phobia = Components.Get<PlayerPhobia>();
return _phobia;
}
// ---- Growing --------------------------------------------------------------------------------
protected override void OnStart()
{
if ( Scene.IsEditor ) return;
_player = Components.Get<ReptileController>() ?? Sump.Player;
Sync( false );
_started = true;
}
protected override void OnEnabled()
{
if ( Scene.IsEditor ) return;
SumpState.MisfitHealed += OnHealed;
}
protected override void OnDisabled()
{
SumpState.MisfitHealed -= OnHealed;
foreach ( var graft in _grafts )
if ( graft.IsValid() && graft.Ability.IsValid() ) graft.Ability.Cancel();
LetGo();
}
protected override void OnDestroy()
{
SumpState.MisfitHealed -= OnHealed;
LetGo();
ClearBeacons();
}
void OnHealed( MisfitProfile profile )
{
if ( !this.IsValid() || !_started ) return;
Sync( true );
}
/// <summary>
/// Makes the grafts match who is healed: one for each healed misfit that has none (with the
/// ceremony, if asked), and none for anybody who is no longer in the Sump (a new run).
/// </summary>
void Sync( bool ceremony )
{
if ( !_player.IsValid() ) return;
// A new Sump was rolled: yesterday's friends are gone.
for ( int i = _grafts.Count - 1; i >= 0; i-- )
{
var graft = _grafts[i];
if ( graft.IsValid() && graft.Source is not null && graft.Source.Healed && SumpState.Misfits.Contains( graft.Source ) ) continue;
Remove( graft );
_grafts.RemoveAt( i );
}
// In the order they were grafted in earlier sittings, then anybody new.
var healed = SumpState.Healed.ToList();
var order = SumpState.GetNote( OrderNote ).Split( ',', StringSplitOptions.RemoveEmptyEntries )
.Select( s => int.TryParse( s, out int index ) ? index : -1 ).ToList();
healed = healed.OrderBy( m => { int at = order.IndexOf( m.Index ); return at < 0 ? int.MaxValue : at; } ).ThenBy( m => m.Index ).ToList();
int grown = 0;
foreach ( var profile in healed )
{
if ( _grafts.Any( g => g.Source == profile ) ) continue;
int variant = _grafts.Count( g => g.Plan == profile.Plan );
float delay = ceremony ? CeremonyDelay + grown * 2.5f : 0f; // two at once take turns
var graft = Graft.Create( this, profile, _grafts.Count + 1, variant, delay, !ceremony );
graft.On = _activeAll;
_grafts.Add( graft );
grown++;
}
for ( int i = 0; i < _grafts.Count; i++ ) _grafts[i].Slot = i + 1;
if ( grown > 0 || _grafts.Count != order.Count )
SumpState.SetNote( OrderNote, string.Join( ",", _grafts.Select( g => g.Source.Index ) ) );
}
void Remove( Graft graft )
{
if ( !graft.IsValid() ) return;
if ( _player.IsValid() && graft.Source is not null ) _player.SetSpeedFactor( SpeedName( graft ), 1f );
graft.GameObject.Destroy();
}
static string SpeedName( Graft graft ) => "graft_" + (graft.Source?.Index ?? 0);
// ---- Every frame ------------------------------------------------------------------------------
protected override void OnUpdate()
{
if ( Scene.IsEditor ) return;
if ( !_player.IsValid() )
{
_player = Components.Get<ReptileController>() ?? Sump.Player;
if ( !_player.IsValid() ) return;
}
// The event covers a heal as it happens; this catches a Sump that was reset under us.
if ( RealTime.Now >= _nextSync )
{
_nextSync = RealTime.Now + 1f;
bool stale = _grafts.Count != SumpState.HealedCount || _grafts.Any( g => !g.IsValid() || g.Source is null || !g.Source.Healed );
if ( stale )
{
_grafts.RemoveAll( g => !g.IsValid() );
Sync( _started );
}
}
UpdateBeacons();
ApplyUnseenTag();
if ( !_activeAll )
{
_straight = 0f;
return;
}
ReadKeys();
ApplyPassives( Time.Delta );
}
/// <summary>Ability N is on the input action "SlotN", in the order grafted.</summary>
void ReadKeys()
{
if ( _player.InputLocked ) return;
if ( Sump.Mode != SumpMode.Hub && Sump.Mode != SumpMode.Flashback && Sump.Mode != SumpMode.Finale ) return;
int keys = Math.Min( _grafts.Count, 9 );
for ( int i = 0; i < keys; i++ )
{
if ( !Input.Pressed( "Slot" + (i + 1) ) ) continue;
var graft = _grafts[i];
if ( !graft.IsValid() || !graft.On || !graft.Ability.IsValid() ) continue;
if ( graft.Grown01 < 1f ) { Note( $"{graft.Name}'s graft is still growing in. Do not pick at it." ); continue; }
graft.Ability.Press();
}
}
/// <summary>
/// The one place the body plans' passive changes are worked out and written: all active grafts
/// together, each weighted by how far it has grown in.
/// </summary>
void ApplyPassives( float dt )
{
bool onWall = _player.Attached && _player.Up.z < WallUpZ;
UpdateStraight( dt );
float gravity = 1f, jump = 1f, grip = 1f, resistance = 0f, calm = 0f, cushion = 0f, ping = 0f;
float maxSpeed = MathF.Max( MaxSpeedFactor, 1f );
foreach ( var graft in _grafts )
{
if ( !graft.IsValid() ) continue;
string name = SpeedName( graft );
float w = graft.On ? graft.Grown01 : 0f;
if ( w <= 0f )
{
if ( _speedNames.Remove( name ) ) _player.SetSpeedFactor( name, 1f );
continue;
}
var p = graft.Passive;
gravity *= Mix( p.Gravity, w );
jump *= Mix( p.Jump, w );
grip *= Mix( p.Grip, w );
resistance += p.Resistance * w;
calm += p.CalmWhileStill * w;
cushion = MathF.Max( cushion, p.Cushion * w ) + MathF.Min( cushion, p.Cushion * w ) * 0.5f; // a second jelly helps half as much
if ( p.PingEvery > 0f ) ping = ping <= 0f ? p.PingEvery : ping * 0.6f; // a second swarm scouts more often
// Speed: one named factor per graft, so they multiply in the controller with everybody else's.
float speed = p.Speed * (onWall ? p.WallSpeed : 1f) * (1f + (p.StraightSpeed - 1f) * _straight);
speed = Math.Clamp( Mix( speed, w ), 1f / maxSpeed, maxSpeed );
_player.SetSpeedFactor( name, speed );
if ( MathF.Abs( speed - 1f ) >= 0.0001f ) _speedNames.Add( name ); else _speedNames.Remove( name );
}
_player.Gravity = _gravity.Apply( _player.Gravity, Math.Clamp( gravity, MathF.Max( MinGravity, 0.05f ), 3f ) );
_player.JumpSpeed = _jump.Apply( _player.JumpSpeed, Math.Clamp( jump, 0.3f, 2f ) );
grip = Math.Clamp( grip, 0.5f, MathF.Max( MaxGrip, 1f ) );
_player.StickDistance = _stick.Apply( _player.StickDistance, grip );
_player.ReachDistance = _reach.Apply( _player.ReachDistance, grip );
ApplyResistance( Math.Clamp( resistance, 0f, 0.8f ) );
// Fungus: calm comes back faster while still, once nothing is frightening it.
if ( calm > 0f && _player.Velocity.Length < StillSpeed && string.IsNullOrEmpty( Sump.Dread ) )
{
var phobia = Phobia();
if ( phobia.IsValid() ) phobia.Soothe( calm * dt );
}
_cushion = Math.Clamp( cushion, 0f, 0.95f );
// Swarm: a scouting ping every so often, in the hub.
if ( ping > 0f && Sump.Mode == SumpMode.Hub && _sincePing > MathF.Max( ping, 2f ) ) Ping();
}
static float Mix( float factor, float weight ) => 1f + (factor - 1f) * weight;
/// <summary>How straight the lizard has been running: rises while it holds a heading at speed, drops on a turn or a stop.</summary>
void UpdateStraight( float dt )
{
var velocity = _player.Velocity;
float speed = velocity.Length;
if ( speed < _player.Speed * 0.5f )
{
_straight = MathF.Max( 0f, _straight - dt * 3f );
_lastHeading = Vector3.Zero;
return;
}
var heading = velocity / speed;
if ( _lastHeading.LengthSquared > 0.5f && dt > 0f )
{
float turned = MathF.Acos( Math.Clamp( Vector3.Dot( heading, _lastHeading ), -1f, 1f ) ) * 180f / MathF.PI / dt;
if ( turned > StraightTurnLimit ) _straight = MathF.Max( 0f, _straight - dt * 4f );
else _straight = MathF.Min( 1f, _straight + dt / MathF.Max( StraightSeconds, 0.05f ) );
}
_lastHeading = heading;
}
float _cushion;
// Jelly: a hard fall is braked in the last moment before the ground, so the landing is soft.
protected override void OnFixedUpdate()
{
if ( Scene.IsEditor || !_activeAll || _cushion <= 0f || !_player.IsValid() ) return;
if ( _player.Attached || _player.IsLatching || _player.IsPinned ) return;
float falling = -_player.Velocity.z;
if ( falling <= CushionSpeed ) return;
// Is the ground within the next sixth of a second of falling?
var from = _player.WorldPosition + Vector3.Up * _player.Radius;
var to = from + Vector3.Down * (falling * 0.16f + _player.Radius + 6f);
var trace = Scene.Trace.Ray( from, to ).IgnoreGameObjectHierarchy( GameObject ).WithoutTags( "debris" ).Run();
if ( !trace.Hit ) return;
float excess = falling - CushionSpeed;
_player.Lunge( Vector3.Up, excess * _cushion * Math.Clamp( Time.Delta * 14f, 0f, 1f ) );
}
/// <summary>Our share of the phobia's resistance, added on top of whatever anybody else set.</summary>
void ApplyResistance( float want )
{
if ( want <= 0f && !_resistanceOn ) return;
var phobia = Phobia();
if ( !phobia.IsValid() ) return;
float current = phobia.Resistance;
// Still what we wrote: take our old share off. Otherwise somebody else set it; start from that.
float theirs = _resistanceOn && MathF.Abs( current - _resistanceWritten ) < 0.0005f ? current - _resistanceGiven : current;
theirs = Math.Clamp( theirs, 0f, 1f );
phobia.Resistance = theirs + want;
_resistanceWritten = phobia.Resistance;
_resistanceGiven = _resistanceWritten - theirs;
_resistanceOn = want > 0f;
}
/// <summary>Puts back everything the grafts changed on the controller, the phobia and the body.</summary>
void LetGo()
{
if ( _player.IsValid() )
{
foreach ( var name in _speedNames ) _player.SetSpeedFactor( name, 1f );
foreach ( var graft in _grafts )
if ( graft.IsValid() ) _player.SetSpeedFactor( SpeedName( graft ), 1f );
_player.Gravity = _gravity.Restore( _player.Gravity );
_player.JumpSpeed = _jump.Restore( _player.JumpSpeed );
_player.StickDistance = _stick.Restore( _player.StickDistance );
_player.ReachDistance = _reach.Restore( _player.ReachDistance );
}
_speedNames.Clear();
if ( _resistanceOn ) ApplyResistance( 0f );
_cushion = 0f;
_straight = 0f;
// The abilities undo themselves when they are disabled, but make sure nothing is left behind.
_unwatchedBy.Clear();
_toyUnseenBy.Clear();
ApplyUnseenTag();
_toyBy.Clear();
ApplyBodyScale();
if ( _ghostBy.Count > 0 ) { _ghostBy.Clear(); GhostOff(); }
}
// ---- Unseen, toy, ghost -------------------------------------------------------------------
void ApplyUnseenTag()
{
bool want = Unseen && _activeAll;
if ( want == _tagged ) return;
_tagged = want;
if ( want ) GameObject.Tags.Add( UnseenTag );
else GameObject.Tags.Remove( UnseenTag );
}
void ApplyBodyScale()
{
float scale = 1f;
foreach ( float s in _toyBy.Values ) scale = MathF.Min( scale, s );
BodyScale = scale;
var body = _player.IsValid() ? _player.Body : null;
if ( !body.IsValid() ) return;
if ( scale < 0.999f )
{
if ( !_bodyScaled ) { _bodyScaled = true; _bodyScaleWas = body.LocalScale; }
body.LocalScale = _bodyScaleWas * scale;
}
else if ( _bodyScaled )
{
_bodyScaled = false;
body.LocalScale = _bodyScaleWas;
}
}
void GhostOn()
{
var body = _player.IsValid() && _player.Body.IsValid() ? _player.Body : null;
if ( body is null ) return;
foreach ( var renderer in body.Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
{
if ( !renderer.IsValid() ) continue;
_ghosted.Add( (renderer, renderer.Tint) );
float k = Math.Clamp( GhostTint, 0f, 1f );
renderer.Tint = new Color( renderer.Tint.r * k, renderer.Tint.g * k, renderer.Tint.b * k, renderer.Tint.a );
}
}
void GhostOff()
{
foreach ( var (renderer, was) in _ghosted )
if ( renderer.IsValid() ) renderer.Tint = was;
_ghosted.Clear();
}
// ---- The swarm's ping -----------------------------------------------------------------------
/// <summary>A thin bright beam over every unhealed misfit in range, in its own colour, for a few seconds.</summary>
void Ping()
{
_sincePing = 0;
ClearBeacons();
_lastPing.Clear();
var here = _player.WorldPosition;
foreach ( var misfit in Misfit.All )
{
if ( !misfit.IsValid() || misfit.Healed ) continue;
var at = misfit.WorldPosition;
if ( (at - here).Length > PingRange ) continue;
_lastPing.Add( at );
var tint = Color.Lerp( misfit.Profile?.Primary ?? Color.White, Color.White, 0.6f );
var beam = Sump.Box( null, "Graft Ping", at + Vector3.Up * 260f, new Vector3( 5f, 5f, 360f ), tint, false );
_beacons.Add( (beam, Time.Now) );
if ( _beacons.Count >= 16 ) break;
}
if ( _lastPing.Count > 0 ) Sump.Sfx( "graft_ping", here, 0.6f );
}
void UpdateBeacons()
{
if ( _beacons.Count == 0 ) return;
float life = MathF.Max( PingSeconds, 0.2f );
for ( int i = _beacons.Count - 1; i >= 0; i-- )
{
var (go, born) = _beacons[i];
float age = (Time.Now - born) / life;
if ( !go.IsValid() || age >= 1f )
{
if ( go.IsValid() ) go.Destroy();
_beacons.RemoveAt( i );
continue;
}
// Thins away to nothing.
float thick = 5f * (1f - age) * (0.8f + 0.2f * MathF.Sin( Time.Now * 20f ));
go.WorldScale = new Vector3( MathF.Max( thick, 0.2f ), MathF.Max( thick, 0.2f ), 360f ) / 50f;
}
}
void ClearBeacons()
{
foreach ( var (go, _) in _beacons ) if ( go.IsValid() ) go.Destroy();
_beacons.Clear();
}
/// <summary>
/// Our share of a number on the controller that other code also sets. The value we find is
/// taken as everybody else's, unless it is still exactly what we wrote last time; ours is
/// multiplied on top, and taken off again by <see cref="Restore"/>.
/// </summary>
sealed class Share
{
float _base, _written;
bool _active;
public float Apply( float current, float factor )
{
if ( !_active || MathF.Abs( current - _written ) > 0.0001f * MathF.Max( 1f, MathF.Abs( current ) ) ) _base = current;
_active = true;
_written = _base * factor;
return _written;
}
public float Restore( float current )
{
if ( !_active ) return current;
_active = false;
return MathF.Abs( current - _written ) > 0.0001f * MathF.Max( 1f, MathF.Abs( current ) ) ? current : _base;
}
}
}