Rampage/World/Toppler.cs

A tall destructible structure (steeple, water tower, silo, billboard) implementing IRampageTarget. Takes damage in Hit, then RampageWorld ticks Tick to sway it or rotate it about its foot until it lands flat, flattening targets along the fall line and playing kind-specific effects (flood, grain burst, bell).

using System;
using System.Collections.Generic;

/// <summary>What a toppler does once it is down.</summary>
public enum TopplerKind { Plain, Steeple, WaterTower, Silo, Billboard }

/// <summary>A tall thing before it is built: where it stands, what it looks like, what it scores.</summary>
public sealed class TopplerPlan
{
	public string Label;
	public float Points, Health = 300f;
	public Vector3 Base;
	public float Yaw;
	public TopplerKind Kind;
	/// <summary>Only what is above this height is solid: the lizard walks between the legs of a water tower.</summary>
	public float SolidFrom;
	public string Landmark;
	public readonly TownShape Shape = new();
}

/// <summary>
/// Something tall that goes over in one piece: the steeple, the water tower, the silo, a
/// billboard. Hit hard enough, it hinges at its foot and falls along the blow, slowly at first,
/// and flattens whatever is lying where it lands. The water tower then floods the street.
///
/// It has no update of its own: <see cref="RampageWorld"/> ticks it while it sways or falls.
/// </summary>
[Title( "Rampage Toppler" ), Category( "Rampage" ), Icon( "signal_cellular_null" )]
public sealed class Toppler : Component, IRampageTarget
{
	public TopplerPlan Plan { get; private set; }

	RampageWorld _world;
	BoxCollider _collider;
	Rotation _upright;
	Vector3 _direction = Vector3.Forward;
	float _health, _angle, _speed, _sway, _nextHit, _radius;
	bool _falling, _down;

	public bool Ticking { get; set; }

	// ---- IRampageTarget ------------------------------------------------------------------------

	public bool Alive => !_falling && !_down && Plan is not null;
	public float Radius => _radius;

	/// <summary>The point up its middle level with the lizard.</summary>
	public Vector3 Centre
	{
		get
		{
			var player = Rampage.Player;
			float z = player.IsValid() ? player.WorldPosition.z - WorldPosition.z + 30f : 40f;
			return WorldPosition + Vector3.Up * Math.Clamp( z, 40f, MathF.Max( Plan.Shape.Height, 40f ) );
		}
	}

	/// <summary>Called once by the world, straight after the object is made at the plan's base.</summary>
	public void Raise( RampageWorld world, TopplerPlan plan )
	{
		_world = world;
		Plan = plan;
		_health = plan.Health;
		_upright = WorldRotation;

		var shape = plan.Shape;
		shape.Bake( world.Kit );
		for ( int i = 0; i < shape.Models.Length; i++ )
			if ( shape.Models[i] is not null ) world.Kit.Draw( GameObject, shape.Models[i], shape.Tints[i] );

		var size = shape.Size;
		_radius = MathF.Max( MathF.Sqrt( size.x * size.x + size.y * size.y ) * 0.5f, 80f );

		_collider = Components.Create<BoxCollider>();
		float solidFrom = MathF.Min( plan.SolidFrom, shape.Maxs.z - 10f );
		float solidHeight = shape.Maxs.z - MathF.Max( shape.Mins.z, solidFrom );
		_collider.Center = shape.Centre.WithZ( shape.Maxs.z - solidHeight * 0.5f );
		_collider.Scale = size.WithZ( solidHeight );
		_collider.Static = true;

		Rampage.Register( this );
	}

	public void Hit( Vector3 velocity, float damage, Vector3 at )
	{
		if ( _falling || _down || !_world.IsValid() ) return;
		float now = Time.Now;
		if ( now < _nextHit ) return;
		_nextHit = now + 0.08f;

		// It will fall the way it was hit, or failing that away from where it was hit.
		var along = velocity.WithZ( 0f );
		if ( along.LengthSquared < 100f ) along = (WorldPosition - at).WithZ( 0f );
		_direction = along.LengthSquared > 0.01f ? along.Normal : Vector3.Forward;

		_health -= _world.Force( velocity, damage );
		_sway = 1f;
		_world.Wake( this );

		if ( _health > 0f )
		{
			TownKit.Play( "building_hit", at, 0.15f );
			return;
		}

		_falling = true;
		_angle = 0.02f;
		_speed = 0.2f;
		Rampage.Unregister( this );
		if ( _collider.IsValid() ) _collider.Enabled = false;
		TownKit.Play( "topple_creak", WorldPosition );
	}

	/// <summary>One frame of swaying or falling. False once it is at rest.</summary>
	public bool Tick( float dt )
	{
		if ( _down ) return false;

		if ( !_falling )
		{
			// A hit that did not fell it: it shivers.
			_sway = MathF.Max( 0f, _sway - dt * 2.5f );
			WorldRotation = TownKit.Tip( _direction, MathF.Sin( Time.Now * 28f ) * 0.025f * _sway ) * _upright;
			return _sway > 0f;
		}

		_speed += (0.5f + 4.5f * MathF.Sin( _angle )) * dt;
		_angle += _speed * dt;
		if ( _angle >= MathF.PI * 0.5f )
		{
			_angle = MathF.PI * 0.5f;
			WorldRotation = TownKit.Tip( _direction, _angle ) * _upright;
			Land();
			return false;
		}

		WorldRotation = TownKit.Tip( _direction, _angle ) * _upright;
		return true;
	}

	void Land()
	{
		_down = true;
		_world.StructureFell( Plan.Landmark, Plan.Label );

		var shape = Plan.Shape;
		float height = shape.Height;
		float width = MathF.Max( MathF.Max( shape.Size.x, shape.Size.y ), 60f );
		var foot = WorldPosition;

		// Everything along the line it fell on is flattened, each thing once.
		var flattened = new HashSet<IRampageTarget>();
		var under = Rampage.Borrow();
		float step = MathF.Max( width, 150f );
		for ( float d = step * 0.5f; d <= height; d += step )
		{
			var p = foot + _direction * d + Vector3.Up * 30f;
			_world.Fx.Dust( p, new Vector3( width, width, 20f ) * 0.5f, 3 );
			Rampage.TargetsNear( p, width * 0.5f, under );
			for ( int i = 0; i < under.Count; i++ )
			{
				var target = under[i];
				if ( ReferenceEquals( target, this ) || !flattened.Add( target ) ) continue;
				_world.Strike( target, _direction * 320f + Vector3.Down * 150f, _world.FlattenDamage, p, d / 6000f );
			}
		}
		Rampage.Return( under );

		var middle = foot + _direction * (height * 0.5f) + Vector3.Up * 40f;
		Rampage.Score( middle, Plan.Points, Plan.Label );
		_world.ShakeAt( middle, 0.8f );
		TownKit.Play( "topple_crash", middle );
		_world.Fx.Rubble( middle, _direction * (height * 0.4f) + new Vector3( width, width, 30f ) * 0.5f, Vector3.Up * 300f + _direction * 150f, 8, 36f,
			shape.RandomColour( Color.White ), shape.RandomColour( Color.White ) );

		var head = foot + _direction * (height * 0.85f);
		switch ( Plan.Kind )
		{
			case TopplerKind.WaterTower:
				_world.Fx.Flood( head.WithZ( foot.z ), _world.FloodRadius );
				TownKit.Play( "flood_gush", head );
				break;
			case TopplerKind.Silo:
				_world.Fx.Burst( head + Vector3.Up * 40f, 16, Tone.Corn, 420f, 30f, 70f, 1.6f );
				break;
			case TopplerKind.Steeple:
				TownKit.Play( "church_bell", head );
				break;
		}
	}

	protected override void OnDestroy()
	{
		if ( !_falling && !_down ) Rampage.Unregister( this );
		_down = true;
	}
}