Sump/Grafts/Graft.cs

Defines the Graft component: one healed misfit's part grown onto the player, built out of tinted box/sphere bits on a socket with a per-kind idle animation, plus a growth-in overshoot and the paired GraftAbility. Also provides the Create factory used by Patchwork.

using System;
using System.Collections.Generic;

/// <summary>
/// One graft: a piece of a healed misfit grown onto the lizard. It has two halves. The PART comes
/// from the misfit's body plan: a few tinted boxes and spheres in the misfit's own colours (the
/// same visual language as <see cref="MisfitBody"/>, but only a piece of one), animating itself
/// and riding on a <see cref="GraftSocket"/>. The ABILITY comes from the misfit's twisted ability
/// and is a <see cref="GraftAbility"/> component beside this one. The body plan's passive change
/// to movement is not applied here: <see cref="Patchwork"/> adds up every active graft's
/// <see cref="GraftPassive"/> in one place, so any number combine without fighting.
/// Each graft lives on its own child object of the player, made by <see cref="Create"/>.
/// </summary>
[Title( "Graft" ), Category( "Sump" ), Icon( "healing" )]
public sealed class Graft : Component, IGraft
{
	// ---- IGraft ---------------------------------------------------------------------------------

	public MisfitProfile Source { get; private set; }
	public string Socket => Spot?.Bone ?? "";

	public string Description
	{
		get
		{
			string text = $"{Name}'s {Entry?.PartName ?? "graft"}: {Entry?.PassiveLine ?? ""}";
			if ( Ability.IsValid() ) text += $"  [{Slot}] {Ability.Title}: {Ability.HowTo}";
			return text;
		}
	}

	/// <summary>False while something (a flashback, a cutscene) has switched grafts off: the part is hidden and the ability undone.</summary>
	bool IGraft.Active { get => On; set => On = value; }

	/// <summary>The same switch as <see cref="IGraft.Active"/> (a component already has an Active of its own).</summary>
	public bool On
	{
		get => _active;
		set
		{
			_active = value;
			if ( _part.IsValid() && _part.Enabled != value ) _part.Enabled = value;
			if ( Ability.IsValid() && Ability.Enabled != value ) Ability.Enabled = value; // disabling an ability undoes its effect
		}
	}

	// ---- For Patchwork and the HUD --------------------------------------------------------------

	public Patchwork Owner { get; private set; }
	public BodyPlan Plan => Source?.Plan ?? BodyPlan.GasSac;
	public GraftPlanEntry Entry { get; private set; }
	public GraftSpot Spot { get; private set; }
	public GraftPassive Passive => Entry?.Passive ?? GraftPassive.None;
	public GraftAbility Ability { get; private set; }

	/// <summary>The key it is on: 1 for Slot1, and so on, in the order grafted.</summary>
	public int Slot { get; set; }

	/// <summary>0 not yet grown to 1 settled in. The passive fades in with it; the ability waits for 1.</summary>
	public float Grown01 => Math.Clamp( _grow, 0f, 1f );

	public string Name => string.IsNullOrEmpty( Source?.Name ) ? "Nobody" : Source.Name;
	public Color Primary => Source?.Primary ?? Color.White;
	public Color Secondary => Source?.Secondary ?? Color.Gray;

	/// <summary>World position of the part, for sounds and effects.</summary>
	public Vector3 PartPosition => _part.IsValid() ? _part.WorldPosition : WorldPosition;

	// ---- Tuning ---------------------------------------------------------------------------------

	/// <summary>Seconds the part takes to swell out of the body.</summary>
	[Property] public float GrowSeconds { get; set; } = 1.6f;

	/// <summary>How far past its real size it swells before settling (0.25 = a quarter over).</summary>
	[Property] public float Overswell { get; set; } = 0.25f;

	/// <summary>Size of the whole part against how it was drawn.</summary>
	[Property] public float PartScale { get; set; } = 1f;

	// ---- Making one -----------------------------------------------------------------------------

	/// <summary>
	/// Grows a graft from a healed misfit on the player. Variant is how many grafts of the same
	/// body plan came before it: it picks the next socket in the plan's list, so two of a kind sit
	/// in different places. With a delay it starts unseen and swells out after that many seconds.
	/// </summary>
	public static Graft Create( Patchwork owner, MisfitProfile profile, int slot, int variant, float delay, bool grown )
	{
		var go = new GameObject( owner.GameObject, true, $"Graft: {profile.Name}" );
		go.Flags |= GameObjectFlags.NotSaved;

		var graft = go.Components.Create<Graft>();
		graft.Owner = owner;
		graft.Source = profile;
		graft.Slot = slot;
		graft.Entry = GraftTable.Plan( profile.Plan );
		graft._variant = Math.Max( variant, 0 );
		graft._grow = grown ? 1f : 0f;
		graft._delay = grown ? 0f : MathF.Max( delay, 0f );
		graft._announced = grown;
		graft.Build();

		graft.Ability = GraftTable.CreateAbility( profile.Ability, go );
		if ( graft.Ability.IsValid() ) graft.Ability.Graft = graft;
		return graft;
	}

	// ---- What the part is made of -----------------------------------------------------------------

	public enum BitKind
	{
		/// <summary>Just sits there.</summary>
		Static,
		/// <summary>Swells and sags as it breathes.</summary>
		Bladder,
		/// <summary>Turns slowly about its own length and flashes white now and then.</summary>
		Shard,
		/// <summary>Orbits its rest position.</summary>
		Mote,
		/// <summary>A thin limb hanging loose: sways, and trails back as the lizard runs.</summary>
		Tendril,
		/// <summary>A limb that steps in time with the lizard's stride.</summary>
		Leg,
		/// <summary>A thin limb that twitches.</summary>
		Antenna,
		/// <summary>A slow breath, then a quick puff that flattens it.</summary>
		Cap,
		/// <summary>Drifts up and away, shrinking, then starts again.</summary>
		Spore,
		/// <summary>Blinks.</summary>
		Lamp,
		/// <summary>Bobs in a wave with its neighbours.</summary>
		Ripple,
	}

	public sealed class Bit
	{
		public GameObject Go;
		public ModelRenderer Renderer;
		public BitKind Kind;
		public Vector3 Pos;                 // rest position, or the joint of a limb
		public Vector3 Scale;
		public Rotation Rot = Rotation.Identity;
		public Color Tint;
		public float Phase, Length, A, B;   // A and B mean different things per kind (see Animate)
		public int Index;
	}

	readonly List<Bit> _bits = new();
	GameObject _part;
	Model _box, _sphere;
	Random _rng;
	bool _built, _active = true, _announced;
	int _variant;
	float _grow, _delay, _phase;

	/// <summary>The end of the limb made last, for putting something on the tip of it.</summary>
	public Vector3 LimbEnd { get; private set; }

	/// <summary>Which of the plan's looks this graft got (0 = the first socket's look).</summary>
	public int Style => Spot?.Style ?? 0;

	void Build()
	{
		if ( _built ) return;
		_built = true;

		Entry ??= GraftTable.Plan( Plan );
		_rng = new Random( (Source?.Seed ?? 1) * 7919 + 101 );
		_phase = Rand( 0f, 20f );

		// The nth graft of a plan takes the plan's nth socket. Past the end of the list it starts
		// again, nudged along and up a little so it still does not sit inside an earlier one.
		var spots = Entry.Spots;
		var spot = spots[_variant % spots.Length];
		int lap = _variant / spots.Length;
		Spot = lap == 0 ? spot : new GraftSpot( spot.Bone, spot.Offset + new Vector3( -4f * lap, 0f, 2.5f * lap ), spot.Style );

		_box = Model.Load( "models/dev/box.vmdl" );       // a 50 unit cube
		_sphere = Model.Load( "models/dev/sphere.vmdl" ); // radius 32

		_part = new GameObject( GameObject, true, Entry.PartName );
		_part.Flags |= GameObjectFlags.NotSaved;

		try { Entry.Build?.Invoke( this ); }
		catch ( Exception e ) { Log.Warning( $"Graft: could not build the {Entry.PartName}: {e.Message}" ); }

		_part.Enabled = _active;
		Place();
	}

	public float Rand( float min, float max ) => min + (float)_rng.NextDouble() * (max - min);
	static float Frac( float v ) => v - MathF.Floor( v );

	Bit Add( Model model, string name, BitKind kind, Vector3 position, Vector3 scale, Color tint )
	{
		var go = new GameObject( _part, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalPosition = position;
		go.LocalScale = scale;

		var renderer = go.Components.Create<ModelRenderer>();
		renderer.Model = model;
		renderer.Tint = tint;
		renderer.RenderType = ModelRenderer.ShadowRenderType.Off;

		var bit = new Bit
		{
			Go = go, Renderer = renderer, Kind = kind, Pos = position, Scale = scale, Tint = tint,
			Phase = Rand( 0f, 6.28f ), Index = _bits.Count,
		};
		_bits.Add( bit );
		return bit;
	}

	/// <summary>A box, sized in inches. Positions are from the socket, in the lizard's frame.</summary>
	public Bit Box( string name, BitKind kind, Vector3 position, Vector3 size, Color tint ) =>
		Add( _box, name, kind, position, size / 50f, tint );

	/// <summary>A sphere (or egg), radii in inches.</summary>
	public Bit Ball( string name, BitKind kind, Vector3 position, Vector3 radii, Color tint ) =>
		Add( _sphere, name, kind, position, radii / 32f, tint );

	/// <summary>A thin box that swings about one end. Pitch 90 hangs down, 0 points ahead, negative is raised.</summary>
	public Bit Limb( string name, BitKind kind, Vector3 joint, float length, float thickness, Color tint, float pitch, float yaw )
	{
		var bit = Box( name, kind, joint, new Vector3( length, thickness, thickness ), tint );
		bit.Length = length;
		bit.A = pitch;
		bit.B = yaw;
		Swing( bit, pitch, yaw );
		return bit;
	}

	void Swing( Bit bit, float pitch, float yaw )
	{
		var rotation = new Angles( pitch, yaw, 0f ).ToRotation();
		bit.Go.LocalRotation = rotation;
		LimbEnd = bit.Pos + rotation.Forward * bit.Length;
		bit.Go.LocalPosition = bit.Pos + rotation.Forward * (bit.Length * 0.5f);
	}

	/// <summary>Turns a bit and remembers it as its rest rotation.</summary>
	public void Turn( Bit bit, Rotation rotation )
	{
		bit.Rot = rotation;
		bit.Go.LocalRotation = rotation;
	}

	/// <summary>A small light on the part. Tagged so misfits afraid of light do not fear a friend's lamp.</summary>
	public PointLight Glow( Vector3 position, Color colour, float radius )
	{
		var go = new GameObject( _part, true, "Glow" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalPosition = position;
		go.Tags.Add( MisfitBody.GlowTag );
		var light = go.Components.Create<PointLight>();
		light.LightColor = colour;
		light.Radius = radius;
		light.Shadows = false;
		return light;
	}

	// ---- Living on the lizard ---------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || !_built || !_part.IsValid() ) return;

		// Growing in: nothing for the delay, then it swells out, a little too far, and settles.
		if ( _grow < 1f && _active )
		{
			if ( _delay > 0f ) _delay -= Time.Delta;
			else
			{
				if ( !_announced )
				{
					_announced = true;
					if ( Owner.IsValid() ) Owner.GraftSwelling( this );
				}
				_grow = MathF.Min( 1f, _grow + Time.Delta / MathF.Max( GrowSeconds, 0.05f ) );
			}
		}

		if ( !_part.Enabled ) return;
		var player = Owner.IsValid() ? Owner.Player : null;
		float speed = player.IsValid() ? MathF.Min( player.Velocity.Length, 700f ) : 0f;
		float gait = player.IsValid() ? player.GaitPhase : 0f;
		Animate( Time.Now + _phase, speed, gait );
	}

	// After everything has moved for the frame (and the rig has posed its bones), sit on the socket.
	protected override void OnPreRender()
	{
		if ( Scene.IsEditor || !_built ) return;
		Place();
	}

	void Place()
	{
		if ( !_part.IsValid() || Spot is null ) return;
		var player = Owner.IsValid() ? Owner.Player : null;
		if ( !player.IsValid() ) return;

		float size = Owner.BodyScale;
		GraftSocket.Resolve( player, Spot.Bone, Spot.Offset, size, out var position, out var rotation );
		_part.WorldPosition = position;
		_part.WorldRotation = rotation;

		// Ease out with an overshoot: 0 -> a bit over 1 -> 1.
		float g = Grown01;
		float swell = g >= 1f ? 1f : g <= 0f ? 0f : 1f - MathF.Pow( 1f - g, 3f ) + MathF.Sin( g * MathF.PI ) * Overswell;
		float misfit = Math.Clamp( Source?.Size ?? 1f, 0.8f, 1.25f );
		_part.WorldScale = new Vector3( MathF.Max( swell * size * misfit * PartScale, 0.001f ) );
	}

	void Animate( float t, float speed, float gait )
	{
		float trail = MathF.Min( speed * 0.08f, 38f );  // hanging things swing back as the lizard runs
		float stride = Math.Clamp( speed / 300f, 0.1f, 1f );

		foreach ( var bit in _bits )
		{
			var go = bit.Go;
			if ( !go.IsValid() ) continue;
			float p = bit.Phase;

			switch ( bit.Kind )
			{
				case BitKind.Static:
					break;

				case BitKind.Bladder:
				{
					float s = MathF.Sin( t * 1.5f + p );
					go.LocalScale = new Vector3( bit.Scale.x * (1f + 0.1f * s), bit.Scale.y * (1f + 0.1f * s), bit.Scale.z * (1f + 0.16f * s) );
					go.LocalPosition = bit.Pos + Vector3.Up * (0.8f * s);
					break;
				}

				case BitKind.Shard:
				{
					go.LocalRotation = bit.Rot * Rotation.FromAxis( Vector3.Up, t * bit.A );
					float chime = MathF.Pow( MathF.Max( 0f, MathF.Sin( t * 0.9f + p * 5f ) ), 24f );
					bit.Renderer.Tint = Color.Lerp( bit.Tint, Color.White, chime );
					break;
				}

				case BitKind.Mote:
				{
					// Length is the orbit's radius, A its turns, B how fast it rides up and down.
					float angle = t * bit.A + p;
					float radius = bit.Length * (1f + 0.12f * MathF.Sin( t * 0.7f + p ) + speed / 700f * 0.5f);
					go.LocalPosition = bit.Pos + new Vector3( MathF.Cos( angle ) * radius, MathF.Sin( angle ) * radius, MathF.Sin( t * bit.B + p ) * radius * 0.35f );
					break;
				}

				case BitKind.Tendril:
					// B is the yaw it hangs at. Pointing backwards (yaw near 180) the trail lifts it; elsewhere it sways more.
					Swing( bit, MathF.Max( bit.A - trail, 8f ) + MathF.Sin( t * 1.7f + p ) * 9f, bit.B + MathF.Sin( t * 1.1f + p * 2f ) * 12f );
					break;

				case BitKind.Leg:
				{
					// Legs sharing a parity step together, like the lizard's own.
					float beat = gait * 2f + (bit.Index % 2) * MathF.PI + p * 0.2f;
					if ( speed < 15f ) beat = t * 1.3f + p; // idle: a slow restless shuffle
					float reach = speed < 15f ? 0.25f : stride;
					Swing( bit, bit.A - MathF.Max( 0f, MathF.Cos( beat ) ) * 22f * reach, bit.B + MathF.Sin( beat ) * 24f * reach );
					break;
				}

				case BitKind.Antenna:
					Swing( bit, bit.A + MathF.Sin( t * 9f + p ) * 5f + trail * 0.5f, bit.B + MathF.Sin( t * 5.3f + p ) * 10f );
					break;

				case BitKind.Cap:
				{
					float puff = MathF.Pow( MathF.Max( 0f, MathF.Sin( t * 0.8f + p ) ), 8f );
					go.LocalScale = new Vector3( bit.Scale.x * (1f + puff * 0.12f), bit.Scale.y * (1f + puff * 0.12f), bit.Scale.z * (1f - puff * 0.22f) );
					break;
				}

				case BitKind.Spore:
				{
					float f = Frac( t * 0.3f + p );
					go.LocalPosition = bit.Pos + new Vector3( MathF.Sin( p * 9f + f * 4f ) * 2.5f - trail * 0.2f * f, MathF.Cos( p * 7f + f * 3f ) * 2.5f, f * 12f );
					go.LocalScale = bit.Scale * MathF.Max( 1f - f, 0.02f );
					break;
				}

				case BitKind.Lamp:
					// A is blinks per second; 0 is a steady lamp with a slow shimmer.
					if ( bit.A > 0f ) bit.Renderer.Tint = Frac( t * bit.A + p ) < 0.5f ? bit.Tint : bit.Tint.Darken( 0.8f );
					else bit.Renderer.Tint = Color.Lerp( bit.Tint, Color.White, 0.25f + 0.25f * MathF.Sin( t * 3f + p ) );
					break;

				case BitKind.Ripple:
				{
					// B is its angle round the rim; the wave runs round it.
					float ripple = MathF.Sin( t * 4f - bit.B * 0.035f );
					go.LocalPosition = bit.Pos + Vector3.Up * (ripple * 1.2f) + Vector3.Backward * (trail * 0.12f);
					go.LocalScale = new Vector3( bit.Scale.x, bit.Scale.y, bit.Scale.z * (1f + ripple * 0.3f) );
					break;
				}
			}
		}
	}
}