Sump/Misfits/MisfitAbilities.cs

The hub ability layer for the Sump misfits. Defines an abstract MisfitAbility component with a Kind, a per-ability seeded RNG, a Strength value and a Piece helper for scattering small props, plus the MisfitAbilities table that maps each TwistedAbility enum value to its component. The five concrete abilities drive BodyDoor (seam opening on a timer, suppressed by scare), OnlyWhileWatched (fades out when the camera looks away), ToyStillness (freezes into a toy when the player is close and trust is low), PriceTag (traces round its home and hangs swinging tags) and BulletMagnet (spawns loose bits that drift toward its chest and respawn when they arrive).

using System;
using System.Collections.Generic;

// A misfit's twisted ability, as it shows in the hub: one small component per ability, all behind
// IMisfitAbility, so a misfit can carry any number of them. To add a new one, write one more
// component deriving from MisfitAbility and give it one line in MisfitAbilities.Table.

/// <summary>
/// What every hub ability shares. It has no update of its own: the <see cref="Misfit"/> it sits on
/// ticks it while it is awake in the hub, and feeds <see cref="Strength"/> from its agitation
/// (0 while asleep or out of the hub).
/// </summary>
public abstract class MisfitAbility : Component, IMisfitAbility
{
	public abstract TwistedAbility Kind { get; }
	public MisfitProfile Profile { get; set; }
	/// <summary>0 dormant .. 1 in full effect.</summary>
	public float Strength { get; set; }

	Random _rng;
	protected float Rand( float min, float max )
	{
		_rng ??= new Random( (Profile?.Seed ?? 1) * 31 + 7 + (int)Kind );
		return min + (float)_rng.NextDouble() * (max - min);
	}

	protected static float Approach( float value, float target, float step ) =>
		value < target ? MathF.Min( value + step, target ) : MathF.Max( value - step, target );

	/// <summary>One step, called by the misfit each frame it is awake in the hub.</summary>
	public abstract void Tick( Misfit owner, MisfitBody body, float dt );

	/// <summary>The hub came into or went out of use: show or hide anything this ability left lying about.</summary>
	public virtual void SetShown( bool shown ) { }

	/// <summary>The misfit was healed just now.</summary>
	public virtual void OnHealed( MisfitBody body ) { }

	/// <summary>A small unsolid primitive under a holder, for the loose things abilities scatter about.</summary>
	protected static GameObject Piece( GameObject parent, string model, string name, Vector3 local, Vector3 scale, Color tint )
	{
		var go = new GameObject( parent, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalPosition = local;
		go.LocalScale = scale;
		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = Model.Load( model );
		renderer.Tint = tint;
		renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
		return go;
	}
}

/// <summary>The table of hub abilities: which component stands for which <see cref="TwistedAbility"/>.</summary>
public static class MisfitAbilities
{
	static readonly Dictionary<TwistedAbility, Func<GameObject, MisfitAbility>> Table = new()
	{
		[TwistedAbility.BodyDoor] = go => go.Components.Create<BodyDoorAbility>(),
		[TwistedAbility.OnlyWhileWatched] = go => go.Components.Create<OnlyWhileWatchedAbility>(),
		[TwistedAbility.BulletMagnet] = go => go.Components.Create<BulletMagnetAbility>(),
		[TwistedAbility.PriceTag] = go => go.Components.Create<PriceTagAbility>(),
		[TwistedAbility.ToyStillness] = go => go.Components.Create<ToyStillnessAbility>(),
	};

	/// <summary>Adds (or replaces) the component that stands for an ability.</summary>
	public static void Register( TwistedAbility kind, Func<GameObject, MisfitAbility> make ) => Table[kind] = make;

	/// <summary>Puts an ability's component on an object. Null if nothing is registered for it.</summary>
	public static MisfitAbility Add( GameObject go, TwistedAbility kind, MisfitProfile profile )
	{
		if ( !go.IsValid() || !Table.TryGetValue( kind, out var make ) ) return null;
		var ability = make( go );
		if ( ability.IsValid() ) ability.Profile = profile;
		return ability;
	}
}

/// <summary>The dissected one: now and then its body opens down the middle on a glowing seam. Not while frightened.</summary>
[Title( "Ability: Body Door" ), Category( "Sump" ), Icon( "door_front" )]
public sealed class BodyDoorAbility : MisfitAbility
{
	public override TwistedAbility Kind => TwistedAbility.BodyDoor;

	/// <summary>Seconds between openings, least and most.</summary>
	[Property] public Vector2 DoorEvery { get; set; } = new( 9f, 16f );
	/// <summary>How long it stays open.</summary>
	[Property] public float DoorSeconds { get; set; } = 2.8f;

	float _doorAt = -1f, _open;

	public override void Tick( Misfit owner, MisfitBody body, float dt )
	{
		float now = Time.Now;
		if ( _doorAt < 0f ) _doorAt = now + Rand( DoorEvery.x, DoorEvery.y );

		float want = 0f;
		if ( now >= _doorAt )
		{
			if ( now > _doorAt + DoorSeconds || owner.Scare > 0.5f ) _doorAt = now + Rand( DoorEvery.x, DoorEvery.y );
			else want = 1f;
		}
		_open = Approach( _open, want, dt * 2.5f );
		body.Open = _open * _open * (3f - 2f * _open);
	}
}

/// <summary>The meme: it thins out and is gone when the camera is not on it, and snaps back when looked at. Healed, it stays.</summary>
[Title( "Ability: Only While Watched" ), Category( "Sump" ), Icon( "visibility" )]
public sealed class OnlyWhileWatchedAbility : MisfitAbility
{
	public override TwistedAbility Kind => TwistedAbility.OnlyWhileWatched;

	/// <summary>The camera must point at it this squarely (cosine of the angle) for it to exist.</summary>
	[Property, Range( 0f, 1f )] public float WatchedDot { get; set; } = 0.75f;

	float _exist = 1f;

	public override void Tick( Misfit owner, MisfitBody body, float dt )
	{
		bool seen = owner.Healed || owner.LookDot > WatchedDot;
		_exist = Approach( _exist, seen ? 1f : 0f, dt * (seen ? 10f : 1.2f) );
		body.Fade = _exist;
	}

	public override void OnHealed( MisfitBody body )
	{
		_exist = 1f;
		if ( body.IsValid() ) body.Fade = 1f;
	}
}

/// <summary>Adopted then forgotten: approached by a stranger, it is a small still toy on the floor.</summary>
[Title( "Ability: Toy Stillness" ), Category( "Sump" ), Icon( "toys" )]
public sealed class ToyStillnessAbility : MisfitAbility
{
	public override TwistedAbility Kind => TwistedAbility.ToyStillness;

	/// <summary>It goes still when the player comes inside this.</summary>
	[Property] public float ToyRange { get; set; } = 280f;

	float _toy;

	public override void Tick( Misfit owner, MisfitBody body, float dt )
	{
		bool toy = !owner.Healed && owner.PlayerDistance < ToyRange && owner.Trust < owner.TalkTrust;
		_toy = Approach( _toy, toy ? 1f : 0f, dt * 5f );
		body.Toy = _toy;
	}

	public override void OnHealed( MisfitBody body )
	{
		_toy = 0f;
		if ( body.IsValid() ) body.Toy = 0f;
	}
}

/// <summary>Worshipped then sold: little price tags hang on whatever stands near its home, swinging.</summary>
[Title( "Ability: Price Tag" ), Category( "Sump" ), Icon( "sell" )]
public sealed class PriceTagAbility : MisfitAbility
{
	public override TwistedAbility Kind => TwistedAbility.PriceTag;

	/// <summary>How many tags it hangs.</summary>
	[Property] public int TagCount { get; set; } = 4;
	/// <summary>How far from its home it looks for something to hang one on.</summary>
	[Property] public float Reach { get; set; } = 260f;

	GameObject _things;
	readonly List<GameObject> _tags = new();

	public override void Tick( Misfit owner, MisfitBody body, float dt )
	{
		if ( _tags.Count == 0 ) Hang( owner.HomePosition );

		// They swing harder the more worked up it is.
		float swing = 12f + 8f * Strength;
		float now = Time.Now;
		for ( int i = 0; i < _tags.Count; i++ )
			if ( _tags[i].IsValid() )
				_tags[i].LocalRotation = new Angles( 0f, i * 70f, MathF.Sin( now * 1.8f + i * 2f ) * swing ).ToRotation();
	}

	/// <summary>Tags on walls and junk round its home, or failing that just above the floor.</summary>
	void Hang( Vector3 home )
	{
		_things = Sump.Spawn( "Price Tags", home, GameObject.Parent );
		var paper = new Color( 0.95f, 0.92f, 0.8f );
		int count = Math.Max( TagCount, 1 );

		for ( int i = 0; i < count; i++ )
		{
			var direction = Rotation.FromYaw( i * 360f / count + Rand( -30f, 30f ) ).Forward;
			var from = home + Vector3.Up * Rand( 22f, 40f );
			var tr = Scene.Trace.Ray( from, from + direction * Reach ).IgnoreGameObjectHierarchy( GameObject ).Run();

			Vector3 at;
			if ( tr.Hit ) at = tr.HitPosition + tr.Normal * 3f;
			else
			{
				var over = home + direction * Rand( 70f, 140f );
				var floor = Scene.Trace.Ray( over + Vector3.Up * 40f, over + Vector3.Down * 160f ).IgnoreGameObjectHierarchy( GameObject ).Run();
				at = (floor.Hit ? floor.HitPosition : home) + Vector3.Up * 14f;
			}

			// The holder is the knot; the string and the card hang below it and swing.
			var tag = Sump.Spawn( "Price Tag", at, _things );
			Piece( tag, "models/dev/box.vmdl", "String", new Vector3( 0f, 0f, -3f ), new Vector3( 0.3f, 0.3f, 6f ) / 50f, Color.White );
			Piece( tag, "models/dev/box.vmdl", "Card", new Vector3( 0f, 0f, -8.5f ), new Vector3( 0.5f, 7f, 5f ) / 50f, paper );
			Piece( tag, "models/dev/box.vmdl", "Price", new Vector3( 0.3f, 0f, -8.5f ), new Vector3( 0.3f, 4.5f, 1.2f ) / 50f, new Color( 0.8f, 0.1f, 0.1f ) );
			_tags.Add( tag );
		}
	}

	public override void SetShown( bool shown )
	{
		if ( _things.IsValid() && _things.Enabled != shown ) _things.Enabled = shown;
	}

	protected override void OnDestroy()
	{
		if ( _things.IsValid() ) _things.Destroy();
	}
}

/// <summary>Shot on a farm: small loose bits round it creep toward it, then start again further out.</summary>
[Title( "Ability: Bullet Magnet" ), Category( "Sump" ), Icon( "adjust" )]
public sealed class BulletMagnetAbility : MisfitAbility
{
	public override TwistedAbility Kind => TwistedAbility.BulletMagnet;

	/// <summary>How many loose bits drift about it.</summary>
	[Property] public int Bits { get; set; } = 7;
	/// <summary>They start between these distances from it.</summary>
	[Property] public Vector2 ScatterRange { get; set; } = new( 110f, 230f );

	GameObject _things;
	readonly List<GameObject> _drifters = new();

	public override void Tick( Misfit owner, MisfitBody body, float dt )
	{
		var me = owner.WorldPosition;
		var heart = (me + body.Top) * 0.5f;

		if ( _drifters.Count == 0 )
		{
			_things = Sump.Spawn( "Loose Bits", me, GameObject.Parent );
			var lead = new Color( 0.3f, 0.3f, 0.33f );
			var brass = new Color( 0.75f, 0.6f, 0.25f );
			for ( int i = 0; i < Math.Max( Bits, 1 ); i++ )
			{
				var bit = Sump.Spawn( "Loose Bit", me, _things );
				if ( i % 2 == 0 ) Piece( bit, "models/dev/box.vmdl", "Casing", Vector3.Zero, new Vector3( 3f, 1.2f, 1.2f ) / 50f, brass );
				else Piece( bit, "models/dev/sphere.vmdl", "Shot", Vector3.Zero, new Vector3( 1.3f / 32f ), lead );
				Scatter( bit, me );
				_drifters.Add( bit );
			}
		}

		// The pull is a little stronger the more worked up it is.
		float pull = 0.75f + 0.5f * Strength;
		foreach ( var bit in _drifters )
		{
			if ( !bit.IsValid() ) continue;
			var to = heart - bit.WorldPosition;
			float left = to.Length;
			if ( left < 12f || left > 600f ) { Scatter( bit, me ); continue; }

			// Slow far out, quicker as it closes, turning as it goes.
			bit.WorldPosition += to / left * (dt * pull * (18f + 9000f / (left + 60f)));
			bit.WorldRotation *= Rotation.FromAxis( Vector3.Up, dt * 200f );
		}
	}

	void Scatter( GameObject bit, Vector3 me )
	{
		var out_ = Rotation.FromYaw( Rand( 0f, 360f ) ).Forward * Rand( ScatterRange.x, ScatterRange.y );
		bit.WorldPosition = me + out_ + Vector3.Up * 2f;
		bit.WorldRotation = Rotation.FromYaw( Rand( 0f, 360f ) );
	}

	public override void SetShown( bool shown )
	{
		if ( _things.IsValid() && _things.Enabled != shown ) _things.Enabled = shown;
	}

	protected override void OnDestroy()
	{
		if ( _things.IsValid() ) _things.Destroy();
	}
}