Rampage/Weapon/DongWeapon.Hits.cs

Partial class for the game's dong/flail weapon, the half that handles contact. Sweeps the chain's points and the ball from last position to current to detect hits on IRampageTargets, applies damage and knockback from the real velocity at the contact point, snags the chain on tall props or towers and tears them out, hooks heavy props on the tip and flings them, and leaves scars, dust and sounds while dragging.

using System;
using System.Collections.Generic;

// What the weight hits. Both weapons are swept from where they were to where they are every
// physics step, and whatever is in the way is struck with the real velocity of the part that
// touched it. Also here: what the dong catches on and tears out, and what it hooks and carries.
// See DongWeapon.cs for the whole picture.
public sealed partial class DongWeapon
{
	// ---- Catching, hooking, dragging ----

	/// <summary>
	/// A tall thin thing (a lamppost, a tree, a water tower) met by the middle of the chain going
	/// slower than this (inches a second at the lizard's ordinary size) is not hit: the chain wraps
	/// round it, holds for a moment, and tears it out.
	/// </summary>
	[Property, Group( "Catching" )] public float SnagBelow { get; set; } = 420f;
	[Property, Group( "Catching" )] public float SnagSeconds { get; set; } = 0.32f;
	/// <summary>What tearing it out does: how fast it leaves the ground, and the damage to a tower (times might).</summary>
	[Property, Group( "Catching" )] public float TearSpeed { get; set; } = 1700f;
	[Property, Group( "Catching" )] public float TearDamage { get; set; } = 500f;
	/// <summary>The tip, dragged over a vehicle, hooks it. It then weighs the end down (this much, see <see cref="LizardRig.DongTipLoad"/>)...</summary>
	[Property, Group( "Catching" )] public float HookLoad { get; set; } = 1.2f;
	/// <summary>...until the tip next goes this fast in a swing (inches a second at the lizard's ordinary size), when it is flung off, this much faster than the tip.</summary>
	[Property, Group( "Catching" )] public float FlingSpeed { get; set; } = 300f;
	[Property, Group( "Catching" )] public float FlingBoost { get; set; } = 1.25f;
	/// <summary>Seconds between the scars a dragged dong leaves in the road.</summary>
	[Property, Group( "Catching" )] public float FurrowInterval { get; set; } = 0.16f;

	Vector3[] _lastPoints = Array.Empty<Vector3>();
	Vector3 _lastSack;
	bool _hasSack;
	float _lastSample, _lastSackSample;
	readonly Dictionary<IRampageTarget, float> _cool = new();

	/// <summary>What is near the chain (or the balls) this step. Only the two sweeps use it, one after the other.</summary>
	readonly List<IRampageTarget> _near = new( 64 );

	// Caught on something.
	IRampageTarget _snagTarget;
	float _snagUntil, _nextSnag;

	// Hooked on the end.
	Destructible _hooked;
	float _nextHook, _nextFurrow, _nextDragSound;

	/// <summary>
	/// Sweeps the chain from where it was to where it is now. Each stretch between two points is a
	/// capsule; a target is hit when it is inside the path the capsule swept and that part of the
	/// chain was moving fast enough. The throw comes from the real velocity at the place it touched.
	/// </summary>
	void SweepChain()
	{
		var points = _rig.DongPoints;
		int count = points.Count;
		if ( count < 2 ) { _lastPoints = Array.Empty<Vector3>(); return; }

		float now = Time.Now;
		if ( _lastPoints.Length != count )
		{
			_lastPoints = new Vector3[count];
			for ( int i = 0; i < count; i++ ) _lastPoints[i] = points[i];
			_lastSample = now;
			return;
		}

		// The rig moves it once a rendered frame; nothing new means nothing to sweep.
		if ( points[count - 1] == _lastPoints[count - 1] && points[0] == _lastPoints[0] ) return;
		float dt = Math.Clamp( now - _lastSample, 0.004f, 0.1f );
		_lastSample = now;

		// A teleport (or the chain being laid out afresh) is not a swing.
		bool jumped = (points[0] - _lastPoints[0]).Length > 130f * G;
		float slowest = MinHitSpeed * MathF.Sqrt( G );

		if ( !jumped && Live )
		{
			float widest = _rig.DongRadiusAt( count - 1 );
			var near = _near;
			Rampage.TargetsNear( points[0], _rig.DongLength + widest + 40f * G, near );
			if ( near.Count > 0 )
			{
				for ( int k = 1; k < count; k++ )
				{
					Vector3 a0 = _lastPoints[k - 1], b0 = _lastPoints[k], a1 = points[k - 1], b1 = points[k];
					var va = (a1 - a0) / dt;
					var vb = (b1 - b0) / dt;
					if ( MathF.Max( va.Length, vb.Length ) < slowest ) continue;

					float radius = _rig.DongRadiusAt( k );
					float travel = MathF.Max( (a1 - a0).Length, (b1 - b0).Length );
					int samples = Math.Clamp( (int)MathF.Ceiling( travel / (radius + 16f) ), 1, 6 );

					for ( int n = 0; n < near.Count; n++ )
					{
						var target = near[n];
						if ( !target.Alive || ReferenceEquals( target, _hooked ) || OnCooldown( target ) ) continue;
						var centre = target.Centre;
						float touch = radius + target.Radius;
						for ( int s = 0; s <= samples; s++ )
						{
							float t = (float)s / samples;
							var a = Vector3.Lerp( a0, a1, t );
							var b = Vector3.Lerp( b0, b1, t );
							if ( Closest( a, b, centre, out float along ) > touch ) continue;

							var velocity = Vector3.Lerp( va, vb, along );
							if ( velocity.Length >= slowest ) Strike( target, velocity, Vector3.Lerp( a, b, along ), _power, _knock, k, count );
							break;
						}
					}
				}
			}
		}

		for ( int i = 0; i < count; i++ ) _lastPoints[i] = points[i];
	}

	/// <summary>The same for the balls: one ball swept from where it was to where it is.</summary>
	void SweepSack()
	{
		var point = _rig.SackPoint;
		float now = Time.Now;
		if ( !_hasSack ) { _hasSack = true; _lastSack = point; _lastSackSample = now; return; }
		if ( point == _lastSack ) return;

		float dt = Math.Clamp( now - _lastSackSample, 0.004f, 0.1f );
		_lastSackSample = now;
		var from = _lastSack;
		_lastSack = point;

		var velocity = (point - from) / dt;
		float speed = velocity.Length;
		bool attacking = _balls != BallMode.Hang && _balls != BallMode.Draw || _joint == Joint.Mega || _joint == Joint.Clap || _joint == Joint.SitDown;
		// A jump of the whole giant is not a swing (the slingshot really does go this fast, so that is let through).
		if ( speed < MinHitSpeed * MathF.Sqrt( G ) || !Live || (!attacking && speed * dt > 130f * G) ) return;

		float radius = _rig.SackRadius;
		var near = _near;
		Rampage.TargetsNear( (from + point) * 0.5f, radius + speed * dt * 0.5f, near );
		for ( int n = 0; n < near.Count; n++ )
		{
			var target = near[n];
			if ( !target.Alive || ReferenceEquals( target, _hooked ) || OnCooldown( target ) ) continue;
			if ( Closest( from, point, target.Centre, out float along ) > radius + target.Radius ) continue;
			Strike( target, velocity, Vector3.Lerp( from, point, along ), attacking ? _ballPower : DragPower, attacking ? _ballKnock : 0.6f, -1, 0 );
		}
	}

	bool OnCooldown( IRampageTarget target ) => _cool.TryGetValue( target, out float until ) && Time.Now < until;

	static bool Big( IRampageTarget target ) => target is Building || target is Toppler;

	/// <summary>The chain only wraps round things while it is in the hand, following through or being dragged: a set-piece swing goes straight through them.</summary>
	bool CanSnag => _joint == Joint.None && (_dong == DongMode.Carried || _dong == DongMode.Aim || _dong == DongMode.Follow);

	/// <summary>Tall and thin enough for the chain to wrap round: a tower, or a prop like a lamppost or a tree.</summary>
	static bool Snaggable( IRampageTarget target )
	{
		if ( target is Toppler ) return true;
		return target is Destructible prop && prop.Kind is not null && prop.Kind.Weight == PropWeight.Medium && prop.Kind.Shape.Size.z > 120f;
	}

	/// <summary>
	/// A part of a weapon moving at this velocity has connected. <paramref name="point"/> is which
	/// point of the dong's chain it was (of <paramref name="count"/>), or -1 for the balls.
	/// </summary>
	void Strike( IRampageTarget target, Vector3 velocity, Vector3 at, float power, float knock, int point, int count )
	{
		float now = Time.Now;
		float speed = velocity.Length;
		float felt = speed / SizeSpeed;         // as if at the lizard's ordinary size
		bool dong = point >= 0;
		bool dragging = dong && _joint == Joint.None && _dong == DongMode.Carried;

		// The tip, dragged over a vehicle, hooks it and takes it along.
		if ( dragging && point >= count - 2 && TryHook( target ) ) return;

		// The middle of the chain, not going flat out, wraps round a post instead of breaking it.
		if ( dong && CanSnag && point >= 2 && point < count - 1 && felt < SnagBelow && now >= _nextSnag && !_rig.DongSnagged && Snaggable( target ) )
		{
			Snag( target, point, at );
			return;
		}

		float bonus = dong && now < _crackBonusUntil ? CrackBonus : 1f;
		var throwing = (velocity * (KnockShare * knock)).ClampLength( MaxKnock )
			+ Vector3.Up * MathF.Min( speed * UpShare * knock + UpBase, MaxKnock * 0.6f );
		float damage = felt / 1000f * DamagePerSpeed * Rampage.Might * power * bonus;
		Hit( target, throwing, damage, at );
		_hitCount++;

		// What the weapon feels of it. A building that is still standing stops it: the balls bounce
		// off (see the flail), the dong is knocked back along itself and the giant with it.
		if ( Big( target ) && target.Alive )
		{
			if ( !dong ) _ballHitBig = true;
			else if ( Swinging )
			{
				_rig.DongImpulse( -velocity * 0.45f, Math.Clamp( (float)point / Math.Max( count - 1, 1 ) - 0.2f, 0f, 0.9f ) );
				Shove( -velocity.WithZ( 0f ), MaxShove * G * 0.25f * Math.Clamp( felt / 600f, 0.2f, 1f ) );
			}
		}
		// Dragged over something small, it bounces.
		else if ( dragging ) _rig.DongImpulse( Vector3.Up * (140f * MathF.Sqrt( G )), 0.5f );

		if ( now >= _nextHitSound )
		{
			_nextHitSound = now + 0.1f;
			Play( dong ? "dong_hit" : "sack_hit", at, Math.Clamp( felt / 600f, 0.45f, 1f ), SizePitch( 1f ) );
		}
		// A hard hit has a second, lower thud under it.
		if ( damage >= ShakeDamage * HitStopFrom && now >= _nextThud )
		{
			_nextThud = now + ThudGap;
			Play( dong ? "dong_slam" : "sack_impact", at, 0.75f, SizePitch( 0.7f ) );
		}
		if ( damage >= ShakeDamage * 0.2f && now >= _nextShake )
		{
			_nextShake = now + 0.12f;
			Thump( Math.Clamp( damage / MathF.Max( ShakeDamage, 1f ), 0.1f, 1f ) );
		}
	}

	/// <summary>
	/// Hits one target (never scoring: targets score themselves) and starts its cooldown, so the
	/// same swing, its shockwave and the other weapon cannot all count on the same thing.
	/// </summary>
	void Hit( IRampageTarget target, Vector3 velocity, float damage, Vector3 at )
	{
		if ( target is null || !target.Alive || ReferenceEquals( target, _hooked ) ) return;
		if ( _cool.Count > 400 ) _cool.Clear();
		_cool[target] = Time.Now + HitCooldown;
		target.Hit( velocity, damage, at );
	}

	/// <summary>Everything within a radius of a point is thrown up and outward. Says how many things that was.</summary>
	int Blast( Vector3 at, float radius, float up, float outward, float damage )
	{
		int hits = 0;
		var near = Rampage.Borrow();
		Rampage.TargetsNear( at, radius, near );
		for ( int i = 0; i < near.Count; i++ )
		{
			var target = near[i];
			var away = (target.Centre - at).WithZ( 0f );
			var direction = away.Length > 1f ? away.Normal : Vector3.Zero;
			Hit( target, direction * outward + Vector3.Up * up, damage, target.Centre );
			hits++;
		}
		Rampage.Return( near );
		return hits;
	}

	/// <summary>
	/// Everything within a radius and in front (a little more than a half-circle) is thrown outward
	/// and up, harder the nearer it is. Says how many things that was.
	/// </summary>
	int ArcBlast( Vector3 at, Vector3 forward, float radius, float damage, float outward, float up )
	{
		int hits = 0;
		var near = Rampage.Borrow();
		Rampage.TargetsNear( at, radius, near );
		for ( int i = 0; i < near.Count; i++ )
		{
			var target = near[i];
			var away = (target.Centre - at).WithZ( 0f );
			float distance = away.Length;
			var direction = distance > 1f ? away / distance : forward;
			if ( Vector3.Dot( direction, forward ) < -0.17f && distance > target.Radius ) continue;
			float falloff = 1f - 0.5f * Math.Clamp( distance / MathF.Max( radius, 1f ), 0f, 1f );
			Hit( target, direction * (outward * falloff) + Vector3.Up * (up * falloff), damage * falloff, target.Centre );
			hits++;
		}
		Rampage.Return( near );
		return hits;
	}

	// ---- Caught on something ----------------------------------------------------------------------

	/// <summary>The chain has met a post: it is held there, and the rest of it carries on round.</summary>
	void Snag( IRampageTarget target, int point, Vector3 at )
	{
		_snagTarget = target;
		_snagUntil = Time.Now + SnagSeconds;
		_nextSnag = Time.Now + 1.6f;
		if ( _cool.Count > 400 ) _cool.Clear();
		_cool[target] = Time.Now + SnagSeconds + 0.5f;
		_rig.SnagDong( point, target.Centre.WithZ( at.z ) );
		Play( "dong_wrap", at, 0.9f, SizePitch( 1.1f ) );
		Tell( "snag", 0.5f );
	}

	/// <summary>
	/// A caught chain lets go when its moment is up, when the giant has pulled it taut, or when
	/// what it was round has gone. Letting go tears the thing out of the ground: a prop leaves whole
	/// and breaks where it lands, a tower is brought down.
	/// </summary>
	void WatchSnag()
	{
		if ( _snagTarget is null )
		{
			if ( _rig.DongSnagged ) _rig.FreeDong();
			return;
		}

		var target = _snagTarget;
		bool gone = !target.Alive || (target is Component component && !component.IsValid());
		if ( !gone && Time.Now < _snagUntil && _rig.DongSnagged && _rig.DongSnagStretch < 1.25f ) return;

		_snagTarget = null;
		_rig.FreeDong();
		if ( gone ) return;

		var at = target.Centre;
		var toward = (_controller.WorldPosition - at).WithZ( 0f );
		var pull = (toward.Length > 1f ? toward.Normal : Vector3.Zero) * (TearSpeed * 0.5f) + Vector3.Up * TearSpeed;
		_cool[target] = Time.Now + HitCooldown;
		if ( target is Destructible prop ) prop.Shove( pull );
		else target.Hit( pull, TearDamage * Rampage.Might, at );
		_hitCount++;

		// And the giant is yanked a step toward it.
		Shove( -toward, MaxShove * G * 0.4f );
		_controller.Kick( Vector3.Random * 6f );
		Thump( 0.3f );
		Play( "dong_tear", at, 1f, SizePitch( 1f ) );
		Puff( at.WithZ( _controller.WorldPosition.z ), 3, Reach * 0.05f );
		Tell( "tear", 0.6f );
	}

	// ---- Hooked on the end ---------------------------------------------------------------------------

	/// <summary>A vehicle that is still parked and in one piece, with nothing on the hook already: it is taken along.</summary>
	bool TryHook( IRampageTarget target )
	{
		if ( _hooked.IsValid() || Time.Now < _nextHook ) return false;
		if ( target is not Destructible prop || !prop.Alive || prop.Loose || prop.Kind is null || prop.Kind.Weight != PropWeight.Heavy ) return false;

		_hooked = prop;
		HookedName = prop.Label ?? "SOMETHING";
		Rampage.SetMoving( prop, true );     // it goes where the tip goes from now on
		Play( "dong_hook", prop.WorldPosition, 1f, SizePitch( 1.2f ) );
		Tell( "hook", 0.5f );
		return true;
	}

	/// <summary>
	/// What is on the hook rides the tip, and makes the end heavier. The next time the tip gets up
	/// to speed in a swing it comes off, faster than the tip was going, and is somebody else's problem.
	/// </summary>
	void CarryHooked()
	{
		if ( !_hooked.IsValid() )
		{
			if ( HookedName.Length > 0 ) Unhook( false );
			return;
		}
		// Broken by something else, or knocked loose by a shockwave: it is no longer ours.
		if ( !_hooked.Alive || _hooked.Loose ) { Unhook( false ); return; }

		var tip = _rig.DongTip;
		var lie = tip - _rig.DongRoot;
		_hooked.WorldPosition = tip + Vector3.Up * (_rig.DongRadiusAt( _rig.DongPoints.Count - 1 ) * 0.3f);
		if ( lie.WithZ( 0f ).Length > 1f ) _hooked.WorldRotation = Rotation.FromYaw( YawOf( lie ) + 90f );

		if ( Swinging && TipSpeed / SizeSpeed >= FlingSpeed ) Unhook( true );
	}

	void Unhook( bool fling )
	{
		var prop = _hooked;
		_hooked = null;
		HookedName = "";
		_nextHook = Time.Now + 2f;
		if ( !prop.IsValid() || !prop.Alive ) return;

		if ( fling && _rig.IsValid() )
		{
			var velocity = (_rig.DongTipVelocity * FlingBoost).ClampLength( MaxKnock * 1.2f );
			if ( velocity.z < 300f ) velocity = velocity.WithZ( 300f + velocity.Length * 0.15f );
			prop.Shove( velocity );
			_cool[prop] = Time.Now + 1f;
			Play( "dong_fling", prop.WorldPosition, 1f, SizePitch( 1.1f ) );
			Tell( "fling", Math.Clamp( velocity.Length / MaxKnock, 0.3f, 1f ) );
		}
		else if ( !prop.Loose ) Rampage.SetMoving( prop, false );   // left where it lies
	}

	// ---- Dragging --------------------------------------------------------------------------------------

	/// <summary>
	/// Carried and not swung, the far end drags along the road behind the giant: it leaves a scar,
	/// raises dust and grinds. (What it runs over is hit by the sweep above, at <see cref="DragPower"/>.)
	/// </summary>
	void Furrow()
	{
		if ( !_controller.Attached || Time.Now < _nextFurrow ) return;
		var velocity = _controller.Velocity.WithZ( 0f );
		if ( velocity.Length < _controller.Speed * 0.45f ) return;

		var tip = _rig.DongTip;
		float radius = _rig.DongRadiusAt( _rig.DongPoints.Count - 1 );
		float ground = _controller.WorldPosition.z;
		if ( tip.z - ground > radius * 1.5f ) return;     // it has bounced clear of the road
		_nextFurrow = Time.Now + FurrowInterval;

		Scar( tip.WithZ( ground ), YawOf( velocity ), velocity.Length * FurrowInterval * 1.3f, radius * 0.9f );
		Puff( tip.WithZ( ground ), 1, radius * 0.6f );
		if ( Time.Now >= _nextDragSound )
		{
			_nextDragSound = Time.Now + 0.8f;
			Play( "dong_drag", tip, 0.7f, SizePitch( 1f ) );
		}
	}
}