Rampage/World/Building.cs

A destructible city building for the Rampage game. Raise builds stacked storey meshes with windows, details and a roof, and Hit applies damage that pops windows, buckles storeys downward one at a time, or drops the walls outward like cards on a big enough blow. Ticking is driven externally by RampageWorld and handles falling pieces, wall panel rotation and the damage dealt to targets under a fallen wall.

using System;
using System.Collections.Generic;
using System.Linq;

public enum RoofKind { Flat, Gable }

/// <summary>What a building is before it is built: where, how big, how tough, what it scores.</summary>
public sealed class BuildingPlan
{
	public string Label;
	public float Points;
	/// <summary>The middle of its footprint, on the ground.</summary>
	public Vector3 Centre;
	public float SizeX, SizeY;
	public int Storeys = 1;
	public float StoreyHeight = 120f;
	/// <summary>Damage that buckles one storey.</summary>
	public float StoreyHealth = 150f;
	public Color Wall = Tone.Stone, Glass = Tone.Glass, RoofColour = Tone.Slate;
	public RoofKind Roof;
	/// <summary>Set on the few buildings the HUD should make a fuss about.</summary>
	public string Landmark;

	/// <summary>A box of trim that rides on one storey (or on the roof, storey -1): a sign, a door, a dish.</summary>
	public struct Detail
	{
		public int Storey;
		public Vector3 Centre, Size;
		public Color Colour;
		public Rotation Turn;
	}
	public readonly List<Detail> Details = new();

	public float Height => Storeys * StoreyHeight;

	/// <summary>Trim on a storey (-1 for the roof): the middle of its underside relative to that storey's floor, then its size.</summary>
	public BuildingPlan Add( int storey, float x, float y, float z, float sx, float sy, float sz, Color colour )
	{
		Details.Add( new Detail { Storey = storey, Centre = new Vector3( x, y, z + sz * 0.5f ), Size = new Vector3( sx, sy, sz ), Colour = colour, Turn = Rotation.Identity } );
		return this;
	}

	public BuildingPlan AddTilted( int storey, Vector3 centre, Vector3 size, Color colour, Rotation turn )
	{
		Details.Add( new Detail { Storey = storey, Centre = centre, Size = size, Colour = colour, Turn = turn } );
		return this;
	}
}

/// <summary>
/// A building that comes down in stages. It is a stack of storeys with a roof on top and one box
/// of collision round the lot. Damage first pops a storey's windows, then buckles a storey: it is
/// squashed flat and everything above drops onto it with a thud and a puff of dust, until the
/// whole thing is a heap. One blow big enough to finish it outright does it differently: the
/// walls fall outward like cards and flatten whatever they land on.
///
/// It has no update of its own: <see cref="RampageWorld"/> ticks only buildings that are moving.
/// </summary>
[Title( "Rampage Building" ), Category( "Rampage" ), Icon( "domain_disabled" )]
public sealed class Building : Component, IRampageTarget
{
	/// <summary>A buckled storey is squashed to this much of its height.</summary>
	const float FlatScale = 0.12f;
	const float FallGravity = 1700f;
	/// <summary>Seconds between one storey going and the next, when a blow takes several.</summary>
	const float CollapseGap = 0.45f;

	public BuildingPlan Plan { get; private set; }

	sealed class Piece
	{
		public GameObject Object;
		public ModelRenderer Walls, Windows;
		public float Z, TargetZ, Fall, Squash = 1f, SquashTo = 1f, Jolt;
		public bool Roof, Flat, Popped;
	}

	/// <summary>One wall of a building that is falling like a house of cards.</summary>
	sealed class Panel
	{
		public GameObject Pivot;
		public Vector3 Out;
		public float Angle, Speed, Delay, Height, Reach;
		public bool Down;
	}

	readonly List<Piece> _pieces = new();
	readonly List<Panel> _panels = new();
	RampageWorld _world;
	BoxCollider _collider;
	float _damage, _wobble, _nextHit, _nextCollapse, _cardsAt;
	int _standing, _queued, _aimStorey = -1;
	bool _dead, _cards;

	/// <summary>True while the world has it on its list of moving buildings.</summary>
	public bool Ticking { get; set; }

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

	public bool Alive => !_dead && Plan is not null;
	/// <summary>Half the short side, and a bit: a long building is a row of such circles, not one huge one.</summary>
	public float Radius => MathF.Min( Plan.SizeX, Plan.SizeY ) * 0.58f;

	/// <summary>
	/// The point inside the building nearest the lizard: level with it (so it can be hit from the
	/// street or from its own roof) and as far along the long side as the lizard is.
	/// </summary>
	public Vector3 Centre
	{
		get
		{
			float top = MathF.Max( CurrentHeight, 50f );
			var player = Rampage.Player;
			var local = player.IsValid() ? player.WorldPosition - WorldPosition + Vector3.Up * 30f : new Vector3( 0f, 0f, 40f );

			float slack = MathF.Abs( Plan.SizeX - Plan.SizeY ) * 0.5f;
			var along = Plan.SizeX >= Plan.SizeY
				? new Vector3( Math.Clamp( local.x, -slack, slack ), 0f, 0f )
				: new Vector3( 0f, Math.Clamp( local.y, -slack, slack ), 0f );
			return WorldPosition + along + Vector3.Up * Math.Clamp( local.z, MathF.Min( 40f, top ), top );
		}
	}

	float CurrentHeight
	{
		get
		{
			float height = 0f;
			foreach ( var piece in _pieces )
				if ( !piece.Roof ) height += Plan.StoreyHeight * (piece.Flat ? FlatScale : 1f);
			return height;
		}
	}

	// ---- Building it ---------------------------------------------------------------------------

	/// <summary>Called once by the world, straight after the object is made at the plan's centre.</summary>
	public void Raise( RampageWorld world, BuildingPlan plan )
	{
		_world = world;
		Plan = plan;
		var kit = world.Kit;
		float sx = plan.SizeX, sy = plan.SizeY, h = plan.StoreyHeight;

		// Every storey of one building is the same two meshes: the walls, and a band of windows.
		var walls = new TownMesh();
		walls.Box( new Vector3( 0f, 0f, h * 0.5f ), new Vector3( sx, sy, h ) );

		var glass = new TownMesh();
		int nx = Math.Max( 1, (int)(sx / 130f) ), ny = Math.Max( 1, (int)(sy / 130f) );
		for ( int i = 0; i < nx; i++ )
		{
			float x = -sx * 0.5f + sx / nx * (i + 0.5f);
			foreach ( float side in new[] { -1f, 1f } )
				glass.Box( new Vector3( x, side * sy * 0.5f, h * 0.55f ), new Vector3( sx / nx * 0.5f, 4f, h * 0.4f ) );
		}
		for ( int i = 0; i < ny; i++ )
		{
			float y = -sy * 0.5f + sy / ny * (i + 0.5f);
			foreach ( float side in new[] { -1f, 1f } )
				glass.Box( new Vector3( side * sx * 0.5f, y, h * 0.55f ), new Vector3( 4f, sy / ny * 0.5f, h * 0.4f ) );
		}

		var wallModel = kit.Make( walls );
		var glassModel = kit.Make( glass );

		for ( int s = 0; s < plan.Storeys; s++ )
		{
			var piece = new Piece { Object = kit.Empty( GameObject, "Storey", new Vector3( 0f, 0f, s * h ) ), Z = s * h, TargetZ = s * h };
			piece.Walls = kit.Draw( piece.Object, wallModel, s % 2 == 0 ? plan.Wall : Tone.Shade( plan.Wall, 0.93f ) );
			piece.Windows = kit.Draw( piece.Object, glassModel, plan.Glass, false );
			AddDetails( piece.Object, s );
			_pieces.Add( piece );
		}

		var roof = new TownMesh();
		if ( plan.Roof == RoofKind.Gable ) roof.Gable( Vector3.Zero, sx + 30f, sy + 30f, MathF.Min( sx, sy ) * 0.38f, sx >= sy );
		else roof.Box( new Vector3( 0f, 0f, 6f ), new Vector3( sx + 14f, sy + 14f, 12f ) );

		var top = new Piece { Object = kit.Empty( GameObject, "Roof", new Vector3( 0f, 0f, plan.Height ) ), Z = plan.Height, TargetZ = plan.Height, Roof = true };
		top.Walls = kit.Draw( top.Object, kit.Make( roof ), plan.RoofColour );
		AddDetails( top.Object, -1 );
		_pieces.Add( top );

		_collider = Components.Create<BoxCollider>();
		_collider.Static = true;
		_standing = plan.Storeys;
		FitCollider();

		Rampage.Register( this );
	}

	void AddDetails( GameObject on, int storey )
	{
		foreach ( var detail in Plan.Details )
		{
			if ( detail.Storey != storey ) continue;
			var block = _world.Kit.Block( on, "Detail", detail.Centre, detail.Size, detail.Colour, false );
			block.LocalRotation = detail.Turn;
		}
	}

	void FitCollider()
	{
		float height = MathF.Max( CurrentHeight, 8f );
		_collider.Center = new Vector3( 0f, 0f, height * 0.5f );
		_collider.Scale = new Vector3( Plan.SizeX, Plan.SizeY, height );
	}

	// ---- Being hit -----------------------------------------------------------------------------

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

		int left = _standing - _queued;
		if ( left <= 0 ) return;

		float force = _world.Force( velocity, damage );
		float storey = Plan.StoreyHealth;
		float remaining = storey * left - _damage;

		_wobble = 1f;
		_world.Wake( this );
		TownKit.Play( "building_hit", at, 0.15f );

		// One blow that would finish it, and is big in its own right: down like a house of cards.
		if ( force >= remaining && force >= storey * _world.OneGoFactor )
		{
			FallLikeCards( velocity );
			return;
		}

		_damage += force;

		int hit = StoreyAt( at.z );
		if ( hit >= 0 )
		{
			if ( !_pieces[hit].Popped && _damage >= storey * 0.3f ) PopWindows( _pieces[hit] );
			if ( _aimStorey < 0 ) _aimStorey = hit;
		}

		while ( _damage >= storey && _queued < _standing )
		{
			_damage -= storey;
			_queued++;
		}
	}

	/// <summary>The standing storey at a height in the world, or the lowest one standing. -1 if none.</summary>
	int StoreyAt( float worldZ )
	{
		float z = worldZ - WorldPosition.z;
		int lowest = -1;
		for ( int i = 0; i < _pieces.Count; i++ )
		{
			var piece = _pieces[i];
			if ( piece.Roof || piece.Flat ) continue;
			if ( lowest < 0 ) lowest = i;
			if ( z >= piece.Z && z < piece.Z + Plan.StoreyHeight ) return i;
		}
		return lowest;
	}

	void PopWindows( Piece piece )
	{
		piece.Popped = true;
		if ( piece.Windows.IsValid() ) piece.Windows.Tint = Tone.Dark;

		var at = WorldPosition + Vector3.Up * (piece.Z + Plan.StoreyHeight * 0.55f);
		_world.Fx.Rubble( at, new Vector3( Plan.SizeX, Plan.SizeY, 20f ) * 0.5f, Vector3.Up * 120f, 4, 12f, Plan.Glass );
		TownKit.Play( "glass_smash", at );
		Rampage.Score( at, 5f, "WINDOWS" );
	}

	// ---- Coming down a storey at a time ----------------------------------------------------------

	void Buckle()
	{
		int k = _aimStorey >= 0 && _aimStorey < _pieces.Count && !_pieces[_aimStorey].Flat && !_pieces[_aimStorey].Roof ? _aimStorey : StoreyAt( float.MinValue );
		_aimStorey = -1;
		if ( k < 0 ) return;

		var piece = _pieces[k];
		float h = Plan.StoreyHeight;
		piece.Flat = true;
		piece.SquashTo = FlatScale;
		if ( piece.Windows.IsValid() ) piece.Windows.Enabled = false;
		if ( piece.Walls.IsValid() ) piece.Walls.Tint = Tone.Shade( Plan.Wall, 0.6f );

		// Everything above it drops by what it lost.
		for ( int j = k + 1; j < _pieces.Count; j++ ) _pieces[j].TargetZ -= h * (1f - FlatScale);

		_standing--;
		FitCollider();

		var at = WorldPosition + Vector3.Up * (piece.Z + h * 0.5f);
		var half = new Vector3( Plan.SizeX, Plan.SizeY, h ) * 0.5f;
		_world.Fx.Dust( WorldPosition + Vector3.Up * piece.Z, half, 8 );
		_world.Fx.Rubble( at, half, Vector3.Up * 260f, 8, 34f, Plan.Wall, Tone.Shade( Plan.Wall, 0.7f ), Plan.Glass );
		TownKit.Play( "storey_crunch", at );
		_world.ShakeAt( at, 0.35f );

		if ( Plan.Storeys > 1 ) Rampage.Score( at, Plan.Points * 0.5f / Plan.Storeys, $"{Plan.Label}, FLOOR BY FLOOR" );
		if ( _standing <= 0 ) Die();
	}

	/// <summary>Nothing left standing: it is a heap, with its roof sat askew on top.</summary>
	void Die()
	{
		if ( _dead ) return;
		_dead = true;
		Rampage.Unregister( this );
		_world.StructureFell( Plan.Landmark, Plan.Label );

		var at = WorldPosition + Vector3.Up * 60f;
		Rampage.Score( at, Plan.Storeys > 1 ? Plan.Points * 0.5f : Plan.Points, Plan.Label );
		_world.ShakeAt( at, Math.Clamp( Plan.Points / 1500f, 0.4f, 1f ) );
		TownKit.Play( "building_collapse", at );

		var roof = _pieces[^1];
		if ( roof.Object.IsValid() ) roof.Object.LocalRotation = Rotation.From( 5f, 0f, -6f );
	}

	// ---- Coming down all at once ---------------------------------------------------------------

	void FallLikeCards( Vector3 velocity )
	{
		float height = MathF.Max( CurrentHeight, Plan.StoreyHeight * 0.5f );
		float share = Plan.Storeys > 1 ? 0.5f + 0.5f * _standing / Plan.Storeys : 1f;

		_dead = true;
		_cards = true;
		_cardsAt = Time.Now;
		_queued = 0;
		Rampage.Unregister( this );
		_world.StructureFell( Plan.Landmark, Plan.Label );

		// The storeys go; four loose walls stand in their place for a moment.
		foreach ( var piece in _pieces )
		{
			if ( piece.Roof ) { piece.TargetZ = 10f; continue; }
			if ( piece.Object.IsValid() ) piece.Object.Enabled = false;
		}
		if ( _collider.IsValid() ) _collider.Enabled = false;

		var kit = _world.Kit;
		float sx = Plan.SizeX, sy = Plan.SizeY;
		var push = velocity.WithZ( 0f );
		var walls = new (Vector3 Out, Vector3 Local, Vector3 Size)[]
		{
			(Vector3.Forward, new Vector3( sx * 0.5f, 0f, 0f ), new Vector3( 12f, sy, height )),
			(Vector3.Backward, new Vector3( -sx * 0.5f, 0f, 0f ), new Vector3( 12f, sy, height )),
			(Vector3.Left, new Vector3( 0f, sy * 0.5f, 0f ), new Vector3( sx, 12f, height )),
			(Vector3.Right, new Vector3( 0f, -sy * 0.5f, 0f ), new Vector3( sx, 12f, height )),
		};

		// The wall on the far side of the blow goes first, then the rest in turn.
		int n = 0;
		foreach ( var wall in walls.OrderByDescending( w => Vector3.Dot( w.Out, push ) ) )
		{
			var pivot = kit.Empty( GameObject, "Falling Wall", wall.Local );
			kit.Block( pivot, "Wall", new Vector3( 0f, 0f, height * 0.5f ), wall.Size, n % 2 == 0 ? Plan.Wall : Tone.Shade( Plan.Wall, 0.88f ) );
			_panels.Add( new Panel { Pivot = pivot, Out = wall.Out, Delay = n * 0.09f, Height = height, Reach = MathF.Max( wall.Size.x, wall.Size.y ) } );
			n++;
		}

		var at = WorldPosition + Vector3.Up * MathF.Min( height * 0.5f, 200f );
		Rampage.Score( at, Plan.Points * share * 1.25f, $"{Plan.Label} (IN ONE GO)" );
		_world.ShakeAt( at, Math.Clamp( Plan.Points / 1200f, 0.5f, 1f ) );
		_world.Fx.Dust( WorldPosition, new Vector3( sx, sy, 40f ) * 0.5f, 6 );
		TownKit.Play( "building_collapse", at );
		_world.Wake( this );
	}

	bool TickCards( float dt )
	{
		bool busy = false;
		float since = Time.Now - _cardsAt;
		foreach ( var panel in _panels )
		{
			if ( panel.Down || !panel.Pivot.IsValid() ) continue;
			busy = true;
			if ( since < panel.Delay ) continue;

			// Slow to start and faster the further over it is, like anything falling off its base.
			panel.Speed += (1.5f + 7f * MathF.Sin( panel.Angle )) * dt;
			panel.Angle += panel.Speed * dt;
			if ( panel.Angle >= MathF.PI * 0.5f )
			{
				panel.Angle = MathF.PI * 0.5f;
				panel.Down = true;
				Slam( panel );
			}
			panel.Pivot.LocalRotation = TownKit.Tip( panel.Out, panel.Angle );
		}
		return busy;
	}

	/// <summary>A wall has landed flat: dust, a thump, and bad news for whatever was under it.</summary>
	void Slam( Panel panel )
	{
		var middle = panel.Pivot.WorldPosition + panel.Out * (panel.Height * 0.5f) + Vector3.Up * 20f;
		var side = Vector3.Cross( Vector3.Up, panel.Out );
		var half = panel.Out * (panel.Height * 0.5f) + side * (panel.Reach * 0.5f);
		_world.Fx.Dust( middle, new Vector3( MathF.Abs( half.x ), MathF.Abs( half.y ), 10f ), 6 );
		TownKit.Play( "wall_slam", middle );
		_world.ShakeAt( middle, 0.3f );

		float reach = MathF.Min( MathF.Max( panel.Height, panel.Reach ) * 0.5f, 500f );
		var under = Rampage.Borrow();
		Rampage.TargetsNear( middle, reach * 0.6f, under );
		for ( int i = 0; i < under.Count; i++ )
		{
			var target = under[i];
			if ( ReferenceEquals( target, this ) ) continue;
			// Another building only gets a shove: a town of dominoes would be over too quickly.
			float damage = target is Building || target is Toppler ? _world.FlattenDamage * 0.25f : _world.FlattenDamage;
			_world.Strike( target, panel.Out * 320f + Vector3.Down * 80f, damage, middle );
		}
		Rampage.Return( under );
	}

	// ---- Moving --------------------------------------------------------------------------------

	/// <summary>One frame of a building that is shaking or coming down. False once it is at rest.</summary>
	public bool Tick( float dt )
	{
		float now = Time.Now;
		bool busy = false;

		if ( _cards )
		{
			busy = TickCards( dt );
		}
		else if ( _queued > 0 )
		{
			busy = true;
			if ( now >= _nextCollapse )
			{
				_queued--;
				_nextCollapse = now + CollapseGap;
				Buckle();
			}
		}

		if ( _wobble > 0f )
		{
			_wobble = MathF.Max( 0f, _wobble - dt * 3f );
			busy = true;
		}
		float sway = MathF.Sin( now * 45f ) * 2.5f * _wobble;

		foreach ( var piece in _pieces )
		{
			if ( !piece.Object.IsValid() ) continue;

			if ( piece.Squash > piece.SquashTo )
			{
				piece.Squash = MathF.Max( piece.SquashTo, piece.Squash - dt * 5f );
				busy = true;
			}

			if ( piece.Z > piece.TargetZ )
			{
				piece.Fall += FallGravity * dt;
				piece.Z -= piece.Fall * dt;
				busy = true;
				if ( piece.Z <= piece.TargetZ )
				{
					piece.Z = piece.TargetZ;
					piece.Fall = 0f;
					Land( piece );
				}
			}

			if ( piece.Jolt > 0f )
			{
				piece.Jolt = MathF.Max( 0f, piece.Jolt - dt * 5f );
				busy = true;
			}

			// Squashed things bulge a little; a storey that has just landed dips and springs back.
			float squash = piece.Squash * (1f - 0.14f * piece.Jolt);
			float bulge = 1f + (1f - squash) * 0.05f;
			piece.Object.LocalPosition = new Vector3( piece.Flat ? 0f : sway, 0f, piece.Z );
			piece.Object.LocalScale = new Vector3( bulge, bulge, squash );
		}

		return busy;
	}

	void Land( Piece piece )
	{
		piece.Jolt = 1f;
		var at = WorldPosition + Vector3.Up * piece.Z;
		_world.Fx.Dust( at, new Vector3( Plan.SizeX, Plan.SizeY, 10f ) * 0.5f, 5 );
		TownKit.Play( "storey_thud", at );
		_world.ShakeAt( at, 0.25f );
	}

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