Rampage/World/RampageWorld.cs

The main world component for the Rampage town. Seeds and lays out an 8x8 cell town, builds the floor, daylight and buildings over the first frames on a millisecond budget, and swaps each cell's baked far meshes for real prop objects as the lizard gets close. Also runs the per-frame work: loose prop tracking and freezing, trample kicks, building and toppler ticking, shockwave blows spread across frames, delayed explosions, prop pass-ons and cover point caching.

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

/// <summary>Where one prop stands, before (and whether or not) it is ever made into an object.</summary>
public sealed class PropSpot
{
	public PropKind Kind;
	public Vector3 Position;
	public float Yaw;
	public Color Body;
	public string Label;
}

/// <summary>One square of the town. Its props are one merged mesh until the lizard comes near.</summary>
public sealed class TownCell
{
	public Vector3 Centre;
	public bool Awake;
	public readonly List<PropSpot> Spots = new();
	/// <summary>The far stand-ins: a mesh per colour of everything in the cell.</summary>
	public readonly List<GameObject> Far = new();
	/// <summary>The real props put down here that are still in one piece.</summary>
	public readonly List<Destructible> Live = new();
	/// <summary>How many of its spots have been made real so far (waking is spread over frames).</summary>
	public int Spawned;
}

/// <summary>
/// THE RAMPAGE's playground: a small seeded town on the surface, built when the scene starts, in
/// which everything breaks. This file is the part that runs it; the town itself is laid out in
/// RampageWorld.Town.cs and the town's answer to rising terror is in RampageWorld.Response.cs.
///
/// Cost is kept down in layers, by distance from the lizard:
///  1. Far cells: every prop in the cell is baked into a few meshes. No objects, no physics.
///  2. Near cells (woken once, for good): each prop is an object with a static collider.
///  3. Hit props become rigid bodies, and are frozen again when they come to rest.
/// Buildings are always there, a few meshes each, and only animate while they are coming down.
/// Rubble and dust are pooled and capped (see <see cref="TownFx"/>).
///
/// Nothing is done in one go that can be spread out: the town is raised over the first frames
/// behind the intro's black (<see cref="Ready"/> turns true when it stands), a waking cell's
/// props are made a few a frame, and a shockwave's blows roll outward over a few frames. Each
/// has a budget in milliseconds (see the Cost group).
///
/// Other modules read the layout from the static members: <see cref="Ready"/>,
/// <see cref="PlayerSpawn"/>, <see cref="StreetPoints"/>, <see cref="Landmarks"/>,
/// <see cref="IsStreet"/>, <see cref="Standing"/> and so on.
/// </summary>
[Title( "Rampage World" ), Category( "Rampage" ), Icon( "location_city" )]
public sealed partial class RampageWorld : Component
{
	// ---- Tuning --------------------------------------------------------------------------------

	/// <summary>The town is the same every run for the same seed.</summary>
	[Property, Group( "Town" )] public int Seed { get; set; } = 1987;

	/// <summary>Multiplies the damage of every hit on the town. The first thing to turn if things break too easily or not at all.</summary>
	[Property, Group( "Damage" )] public float DamageScale { get; set; } = 1f;
	/// <summary>Damage a hit does for its speed alone, per inch a second, on top of the damage it carries.</summary>
	[Property, Group( "Damage" )] public float VelocityDamage { get; set; } = 0.02f;
	/// <summary>A blow that finishes a building and is this many storeys' worth by itself takes it in one go.</summary>
	[Property, Group( "Damage" )] public float OneGoFactor { get; set; } = 1.5f;
	/// <summary>Damage done to whatever a falling wall or tower lands on.</summary>
	[Property, Group( "Damage" )] public float FlattenDamage { get; set; } = 260f;
	/// <summary>A shockwave's damage at its centre, per unit of its speed.</summary>
	[Property, Group( "Damage" )] public float ShockDamage { get; set; } = 0.1f;
	/// <summary>A flying prop must hit something this fast to pass the blow on.</summary>
	[Property, Group( "Damage" )] public float PassOnSpeed { get; set; } = 220f;
	/// <summary>How much of its own speed a flying prop gives to what it hits.</summary>
	[Property, Group( "Damage" )] public float PassOnShare { get; set; } = 0.6f;
	/// <summary>Running faster than this, the lizard kicks small props out of its way.</summary>
	[Property, Group( "Damage" )] public float TrampleSpeed { get; set; } = 220f;
	/// <summary>What being kicked aside does to a small prop. Most survive the kick and break where they land.</summary>
	[Property, Group( "Damage" )] public float TrampleDamage { get; set; } = 4f;
	/// <summary>How far the water tower's flood spreads.</summary>
	[Property, Group( "Damage" )] public float FloodRadius { get; set; } = 1500f;

	/// <summary>A cell's props become real objects when the lizard is this close to the cell's edge.</summary>
	[Property, Group( "Cost" )] public float WakeRadius { get; set; } = 2600f;
	/// <summary>Never more props moving as rigid bodies than this; the longest in flight is frozen first.</summary>
	[Property, Group( "Cost" )] public int MaxLoose { get; set; } = 140;
	[Property, Group( "Cost" )] public int MaxChunks { get; set; } = 170;
	[Property, Group( "Cost" )] public int MaxPuffs { get; set; } = 240;
	/// <summary>Most pieces of rubble made in one frame.</summary>
	[Property, Group( "Cost" )] public int ChunksPerFrame { get; set; } = 8;
	/// <summary>Seconds a piece of rubble lies about before it is taken back.</summary>
	[Property, Group( "Cost" )] public float ChunkLife { get; set; } = 11f;
	/// <summary>Size of every piece of debris against what was asked for: chunkier above 1.</summary>
	[Property, Group( "Cost" )] public float ChunkSize { get; set; } = 1.3f;
	/// <summary>Milliseconds a frame spent raising the town at the start, behind the intro's black.</summary>
	[Property, Group( "Cost" )] public float RaiseBudgetMs { get; set; } = 4f;
	/// <summary>Milliseconds a frame spent making a waking cell's props real.</summary>
	[Property, Group( "Cost" )] public float WakeBudgetMs { get; set; } = 1.2f;
	/// <summary>Milliseconds a frame spent on the blows of shockwaves (a few always land, whatever the time).</summary>
	[Property, Group( "Cost" )] public float BlowBudgetMs { get; set; } = 1.5f;
	/// <summary>How fast a shockwave's blows travel outward from its middle, in inches a second.</summary>
	[Property, Group( "Cost" )] public float BlowWaveSpeed { get; set; } = 6000f;

	[Property, Group( "Light" )] public Color SunColor { get; set; } = new( 1f, 0.93f, 0.8f );
	[Property, Group( "Light" )] public float SunIntensity { get; set; } = 1.2f;
	[Property, Group( "Light" )] public Angles SunAngles { get; set; } = new( 52f, 215f, 0f );
	[Property, Group( "Light" )] public Color AmbientColor { get; set; } = new( 0.36f, 0.38f, 0.44f );

	[Property, ReadOnly, Group( "Now" )] public int LooseProps => _loose.Count;
	[Property, ReadOnly, Group( "Now" )] public int AwakeCells => _cells.Count( c => c.Awake );
	[Property, ReadOnly, Group( "Now" )] public int PropCount { get; private set; }

	// ---- The layout, for the other modules -------------------------------------------------------

	public static RampageWorld Current { get; private set; }

	/// <summary>True once the town stands and the lists below are final.</summary>
	public static bool Ready { get; private set; }
	/// <summary>How long raising the town took (real seconds), and the longest frame while it went up (milliseconds).</summary>
	public static float RaisedIn { get; private set; }
	public static float RaiseWorstMs { get; private set; }

	/// <summary>Half the width of the world: nothing and nobody gets further than this from the middle.</summary>
	public const float HalfSize = 8000f;

	/// <summary>The manhole in the central crossroads that the lizard climbs out of (feet position), and the way it faces.</summary>
	public static Vector3 PlayerSpawn { get; private set; }
	public static float PlayerSpawnYaw { get; private set; }

	// [SkipHotload]: a hotload in mid-play cannot carry a list of vectors over (it fails with
	// "Source array is too small" and leaves the list broken), and everybody who then asked for a
	// street threw, every frame. These hold nothing of ours, so they are simply left as they are.
	[SkipHotload] static readonly List<Vector3> _streetPoints = new();
	[SkipHotload] static readonly List<Vector3> _landmarks = new();
	[SkipHotload] static readonly List<string> _landmarkNames = new();
	[SkipHotload] static readonly List<Vector3> _barricades = new();

	/// <summary>Points on the pavements, a few hundred of them, to stand on and flee along. Filled before any OnStart.</summary>
	public static IReadOnlyList<Vector3> StreetPoints => _streetPoints;
	/// <summary>The places worth pointing at, and their names, index for index.</summary>
	public static IReadOnlyList<Vector3> Landmarks => _landmarks;
	public static IReadOnlyList<string> LandmarkNames => _landmarkNames;
	/// <summary>Where the police and the army have parked their roadblocks so far.</summary>
	public static IReadOnlyList<Vector3> Barricades => _barricades;

	[SkipHotload] static readonly List<Vector3> _coverPoints = new();
	static float _coverAt = -100f;

	/// <summary>
	/// Vehicles on the streets near the lizard that are still in one piece and still parked:
	/// something for a frightened person to duck behind. Looked over again every second or two.
	/// </summary>
	public static IReadOnlyList<Vector3> CoverPoints
	{
		get
		{
			var world = Current;
			if ( !world.IsValid() || !world._raised ) return _coverPoints;
			float now = Time.Now;
			if ( now >= _coverAt && now - _coverAt < 1.5f ) return _coverPoints;
			_coverAt = now;
			_coverPoints.Clear();
			foreach ( var cell in world._cells )
			{
				if ( !cell.Awake ) continue;
				for ( int i = 0; i < cell.Live.Count; i++ )
				{
					var prop = cell.Live[i];
					if ( !prop.IsValid() || !prop.Alive || prop.Loose || prop.Kind.Weight < PropWeight.Heavy ) continue;
					var at = prop.WorldPosition;
					if ( IsStreet( at ) ) _coverPoints.Add( at );
				}
			}
			return _coverPoints;
		}
	}

	/// <summary>Buildings and towers still up, and how many there were.</summary>
	public static int Standing { get; private set; }
	public static int Total { get; private set; }

	/// <summary>The town is flat.</summary>
	public static float GroundHeightAt( Vector3 point ) => 0f;

	/// <summary>True on a road or its pavements.</summary>
	public static bool IsStreet( Vector3 p )
		=> MathF.Abs( p.x ) <= TownHalf && MathF.Abs( p.y ) <= TownHalf && (OnRoadAxis( p.x ) || OnRoadAxis( p.y ));

	// ---- State ---------------------------------------------------------------------------------

	// The helpers are made when first asked for, and made again if a hotload has lost one: nobody
	// who asks the town for its kit, its debris or its catalogue is ever handed nothing.
	TownKit _kit;
	TownFx _fx;
	PropCatalogue _props;
	public TownKit Kit => _kit ??= new TownKit();
	public TownFx Fx => _fx is { Sound: true } ? _fx : (_fx = new TownFx( this ));
	public PropCatalogue Props => _props ??= new PropCatalogue();
	/// <summary>Where the rubble and the dust are kept.</summary>
	public GameObject FxRoot => _fxRoot.IsValid() ? _fxRoot : (_fxRoot = Group( "Debris" ));

	const int CellsPerSide = 8;
	const float CellSize = HalfSize * 2f / CellsPerSide;

	readonly List<TownCell> _cells = new();
	readonly List<BuildingPlan> _buildingPlans = new();
	readonly List<TopplerPlan> _topplerPlans = new();
	readonly List<Destructible> _loose = new();
	readonly List<Building> _movingBuildings = new();
	readonly List<Toppler> _movingTopplers = new();
	readonly List<(IRampageTarget Target, Vector3 Velocity, float Damage, Vector3 At)> _passOns = new();
	readonly List<(Vector3 At, float When, float Radius, float Speed)> _booms = new();
	readonly List<TownCell> _waking = new();

	struct Blow { public IRampageTarget Target; public Vector3 Velocity, At; public float Damage, When; }
	readonly List<Blow> _blows = new();

	Sandbox.Diagnostics.FastTimer _clock;   // the engine timer: the sandbox does not allow System.Diagnostics.Stopwatch
	IEnumerator<bool> _raising;
	float _raiseBegan;
	int _raiseFrames;

	GameObject _ground, _groundArt, _propRoot, _structures, _fxRoot, _sky;
	Random _rng = new( 1 );
	bool _raised, _raiseBegun, _playerPlaced, _subscribed;

	// ---- Starting up ---------------------------------------------------------------------------

	protected override void OnAwake()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		Ready = false;
		_streetPoints.Clear();
		_landmarks.Clear();
		_landmarkNames.Clear();
		_barricades.Clear();
		_coverPoints.Clear();
		_coverAt = -100f;

		// The plan is only numbers, so it is drawn up at once: the lists are there for everyone's
		// OnStart. So is the floor, so nobody falls through the world on the first frame.
		_rng = new Random( Seed );
		_props = new PropCatalogue();
		for ( int y = 0; y < CellsPerSide; y++ )
			for ( int x = 0; x < CellsPerSide; x++ )
				_cells.Add( new TownCell { Centre = new Vector3( -HalfSize + (x + 0.5f) * CellSize, -HalfSize + (y + 0.5f) * CellSize, 0f ) } );

		PlanTown();
		Total = Standing = _buildingPlans.Count + _topplerPlans.Count;
		PropCount = _cells.Sum( c => c.Spots.Count );
		BuildFloor();
	}

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Rampage.Shockwave += OnShockwave;
		Rampage.TierUp += OnTierUp;
		_subscribed = true;
	}

	protected override void OnDestroy()
	{
		if ( _subscribed )
		{
			Rampage.Shockwave -= OnShockwave;
			Rampage.TierUp -= OnTierUp;
		}
		if ( Current == this )
		{
			Current = null;
			Ready = false;
		}
	}

	GameObject Group( string name )
	{
		var go = new GameObject( GameObject, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.WorldPosition = Vector3.Zero;
		go.WorldRotation = Rotation.Identity;
		return go;
	}

	/// <summary>Clears away a half-raised town, so that it can be raised again from the plan.</summary>
	void ScrapRaise()
	{
		if ( _groundArt.IsValid() ) _groundArt.Destroy();
		if ( _propRoot.IsValid() ) _propRoot.Destroy();
		if ( _structures.IsValid() ) _structures.Destroy();
		if ( _fxRoot.IsValid() ) _fxRoot.Destroy();
		if ( _sky.IsValid() ) _sky.Destroy();
		_groundArt = _propRoot = _structures = _fxRoot = _sky = null;
		_fx = null;
		_kit = null;

		foreach ( var cell in _cells )
		{
			cell.Awake = false;
			cell.Spawned = 0;
			cell.Live.Clear();
			cell.Far.Clear();
		}
		_waking.Clear(); _loose.Clear(); _movingBuildings.Clear(); _movingTopplers.Clear();
		_passOns.Clear(); _booms.Clear(); _blows.Clear(); _sirens.Clear();
		Standing = Total;
	}

	/// <summary>Solid ground under everything, and unseen walls and a lid at the edge of the world.</summary>
	void BuildFloor()
	{
		_ground = Group( "Ground" );

		void Solid( string name, Vector3 centre, Vector3 size )
		{
			var go = new GameObject( _ground, true, name );
			go.Flags |= GameObjectFlags.NotSaved;
			go.WorldPosition = centre;
			var collider = go.Components.Create<BoxCollider>();
			collider.Scale = size;
			collider.Static = true;
		}

		const float thick = 200f, high = 5000f;
		float span = Outer * 2f;
		Solid( "Floor", new Vector3( 0f, 0f, -thick * 0.5f ), new Vector3( span, span, thick ) );
		Solid( "Lid", new Vector3( 0f, 0f, high + thick * 0.5f ), new Vector3( span, span, thick ) );
		foreach ( float side in new[] { -1f, 1f } )
		{
			Solid( "Edge", new Vector3( side * (HalfSize + thick * 0.5f), 0f, high * 0.5f ), new Vector3( thick, span, high ) );
			Solid( "Edge", new Vector3( 0f, side * (HalfSize + thick * 0.5f), high * 0.5f ), new Vector3( span, thick, high ) );
		}
	}

	/// <summary>
	/// Makes everything that is drawn. Done on the first frame update, not while the scene is still
	/// waking: meshes made that early have been seen not to draw.
	/// </summary>
	/// <remarks>
	/// It is written as a list of small steps (each "yield" is the end of one), and
	/// <see cref="OnUpdate"/> takes as many steps a frame as fit in <see cref="RaiseBudgetMs"/>,
	/// so the first seconds never freeze.
	/// </remarks>
	IEnumerator<bool> RaiseTown()
	{
		_kit = new TownKit();
		_groundArt = Group( "Ground Art" );
		_propRoot = Group( "Props" );
		_structures = Group( "Buildings" );
		_fxRoot = Group( "Debris" );
		_sky = Group( "Daylight" );
		_fx = new TownFx( this );
		yield return true;

		BuildGround();
		yield return true;
		BuildDaylight();
		yield return true;

		foreach ( var plan in _buildingPlans )
		{
			var go = Kit.Empty( _structures, plan.Label, plan.Centre );
			go.Components.Create<Building>().Raise( this, plan );
			yield return true;
		}

		foreach ( var plan in _topplerPlans )
		{
			var go = Kit.Empty( _structures, plan.Label, plan.Base );
			go.WorldRotation = Rotation.FromYaw( plan.Yaw );
			go.Components.Create<Toppler>().Raise( this, plan );
			yield return true;
		}

		// Everything round the spawn is real from the start; the rest is baked for now.
		foreach ( var cell in _cells )
		{
			if ( !Near( cell, PlayerSpawn ) ) { BakeFar( cell ); yield return true; continue; }

			cell.Awake = true;
			while ( cell.Spawned < cell.Spots.Count )
			{
				Spawn( cell.Spots[cell.Spawned++], cell );
				if ( (cell.Spawned & 3) == 0 ) yield return true;
			}
			yield return true;
		}

		// The rubble and the dust are made now, switched off, so the first building to fall costs nothing.
		while ( Fx.Prewarm( 6 ) ) yield return true;
	}

	void BuildDaylight()
	{
		// Only what the scene does not already have.
		if ( !Scene.GetAllComponents<DirectionalLight>().Any() )
		{
			var sun = Kit.Empty( _sky, "Sun" );
			sun.WorldRotation = SunAngles.ToRotation();
			var light = sun.Components.Create<DirectionalLight>();
			light.LightColor = SunColor;
			light.Intensity = SunIntensity;
			light.Shadows = true;
		}

		if ( !Scene.GetAllComponents<AmbientLight>().Any() )
			Kit.Empty( _sky, "Ambient" ).Components.Create<AmbientLight>().Color = AmbientColor;

		if ( !Scene.GetAllComponents<SkyBox2D>().Any() )
		{
			var material = Material.Load( "materials/skybox/skybox_day_01.vmat" );
			if ( material is not null )
			{
				var skybox = Kit.Empty( _sky, "Sky" ).Components.Create<SkyBox2D>();
				skybox.SkyMaterial = material;
				skybox.SkyIndirectLighting = true;
			}
		}
	}

	// ---- Cells: far meshes and real props ----------------------------------------------------------

	TownCell CellAt( Vector3 p )
	{
		int x = Math.Clamp( (int)((p.x + HalfSize) / CellSize), 0, CellsPerSide - 1 );
		int y = Math.Clamp( (int)((p.y + HalfSize) / CellSize), 0, CellsPerSide - 1 );
		return _cells[y * CellsPerSide + x];
	}

	bool Near( TownCell cell, Vector3 p )
	{
		float reach = CellSize * 0.5f + WakeRadius;
		return MathF.Abs( p.x - cell.Centre.x ) < reach && MathF.Abs( p.y - cell.Centre.y ) < reach;
	}

	/// <summary>The cell as seen from far off: all its props merged into one mesh per colour.</summary>
	void BakeFar( TownCell cell )
	{
		if ( cell.Awake || cell.Spots.Count == 0 ) return;
		var meshes = new Dictionary<int, TownMesh>();
		foreach ( var spot in cell.Spots )
			spot.Kind.Shape.MergeInto( meshes, spot.Position, Rotation.FromYaw( spot.Yaw ), spot.Body );

		foreach ( var mesh in meshes.Values )
		{
			var model = Kit.Make( mesh );
			if ( model is null ) continue;
			var go = Kit.Empty( _propRoot, "Far Props" );
			Kit.Draw( go, model, mesh.Tint, false );
			cell.Far.Add( go );
		}
	}

	/// <summary>
	/// The lizard is near: the cell's props become real, a few a frame (see <see cref="RunWaking"/>),
	/// and its stand-in meshes go once the last of them is there. Once only.
	/// </summary>
	void WakeCell( TownCell cell )
	{
		if ( cell.Awake ) return;
		cell.Awake = true;
		_waking.Add( cell );
	}

	/// <summary>Makes real as many props of the waking cells as the frame's budget allows (always at least one).</summary>
	void RunWaking()
	{
		if ( _waking.Count == 0 ) return;
		_clock = Sandbox.Diagnostics.FastTimer.StartNew();
		while ( _waking.Count > 0 )
		{
			var cell = _waking[0];
			if ( cell.Spawned < cell.Spots.Count ) Spawn( cell.Spots[cell.Spawned++], cell );
			if ( cell.Spawned >= cell.Spots.Count )
			{
				foreach ( var far in cell.Far ) if ( far.IsValid() ) far.Destroy();
				cell.Far.Clear();
				_waking.RemoveAt( 0 );
			}
			if ( _clock.ElapsedMilliSeconds >= WakeBudgetMs ) break;
		}
	}

	Destructible Spawn( PropSpot spot, TownCell cell )
	{
		var go = Kit.Empty( _propRoot, spot.Kind.Name, spot.Position );
		go.WorldRotation = Rotation.FromYaw( spot.Yaw );
		var prop = go.Components.Create<Destructible>();
		prop.Setup( this, spot.Kind, spot.Body, spot.Label, cell );
		cell?.Live.Add( prop );
		if ( spot.Kind.Quirk == PropQuirk.Siren ) _sirens.Add( prop );
		return prop;
	}

	/// <summary>Puts a new prop into the town now, as a real object (the police arriving, say).</summary>
	public Destructible SpawnProp( PropKind kind, Vector3 position, float yaw )
	{
		if ( !_raised || kind is null ) return null;
		var spot = new PropSpot
		{
			Kind = kind, Position = position.WithZ( 0f ), Yaw = yaw,
			Body = kind.BodyColours[Game.Random.Next( kind.BodyColours.Length )],
			Label = kind.Labels[Game.Random.Next( kind.Labels.Length )],
		};
		PropCount++;
		return Spawn( spot, CellAt( position ) );
	}

	// ---- Every frame ---------------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;

		if ( !_raised )
		{
			// The floor is there already, so the lizard can stand in the square while the town goes up.
			if ( !_playerPlaced ) PlacePlayer();

			if ( _raising is null )
			{
				// Begun but with no steps left to take: a hotload lost them half way up. What was
				// built is cleared away and the town is raised again from the plan.
				if ( _raiseBegun ) ScrapRaise();
				_raiseBegun = true;
				_raising = RaiseTown(); _raiseBegan = RealTime.Now; RaiseWorstMs = 0f;
			}
			// The very first frames carry the scene's own loading: only the ones after count.
			if ( ++_raiseFrames > 3 ) RaiseWorstMs = MathF.Max( RaiseWorstMs, RealTime.Delta * 1000f );
			_clock = Sandbox.Diagnostics.FastTimer.StartNew();
			// A few milliseconds a frame; but on a machine (or in a moment) so slow that this would
			// take for ever, more and more, until it is simply finished.
			float raising = RealTime.Now - _raiseBegan;
			float budget = raising > 8f ? 100000f : raising > 3f ? RaiseBudgetMs * 4f : RaiseBudgetMs;
			bool more;
			while ( (more = _raising.MoveNext()) && _clock.ElapsedMilliSeconds < budget ) { }
			if ( more ) return;

			_raising = null;
			_raised = true;
			Ready = true;
			RaisedIn = RealTime.Now - _raiseBegan;
			return;
		}

		float now = Time.Now;
		float dt = Time.Delta;
		var player = Rampage.Player;
		if ( !_playerPlaced ) PlacePlayer();
		// Lost to a hotload, these are simply made again (new props then go under the new ones).
		if ( !_propRoot.IsValid() ) _propRoot = Group( "Props" );
		if ( !_structures.IsValid() ) _structures = Group( "Buildings" );
		var lizard = player.IsValid() ? player.WorldPosition : PlayerSpawn;

		// At most one cell a frame, so running into a new street never hitches much.
		foreach ( var cell in _cells )
		{
			if ( cell.Awake || !Near( cell, lizard ) ) continue;
			WakeCell( cell );
			break;
		}

		if ( player.IsValid() )
		{
			Trample( player );
			KeepIn( player );
		}

		TownCell landing = null;
		for ( int i = _loose.Count - 1; i >= 0; i-- )
		{
			var prop = _loose[i];
			if ( !prop.IsValid() || !prop.TickLoose( now ) ) { _loose.RemoveAt( i ); continue; }

			// A thrown car heading into a street that is still a far mesh: that street becomes real.
			if ( landing is not null ) continue;
			var cell = CellAt( prop.WorldPosition );
			if ( !cell.Awake ) landing = cell;
		}
		if ( landing is not null ) WakeCell( landing );
		RunWaking();

		for ( int i = _movingBuildings.Count - 1; i >= 0; i-- )
		{
			var building = _movingBuildings[i];
			if ( building.IsValid() && building.Tick( dt ) ) continue;
			if ( building.IsValid() ) building.Ticking = false;
			_movingBuildings.RemoveAt( i );
		}

		for ( int i = _movingTopplers.Count - 1; i >= 0; i-- )
		{
			var toppler = _movingTopplers[i];
			if ( toppler.IsValid() && toppler.Tick( dt ) ) continue;
			if ( toppler.IsValid() ) toppler.Ticking = false;
			_movingTopplers.RemoveAt( i );
		}

		RunPassOns();
		RunBooms( now );
		RunBlows( now );
		TickResponse( now );
		Fx.Tick( dt );
	}

	void PlacePlayer()
	{
		var player = Rampage.Player;
		if ( !player.IsValid() ) return;
		player.Teleport( PlayerSpawn, PlayerSpawnYaw );
		_playerPlaced = true;
	}

	/// <summary>Running through the small stuff sends it flying instead of stopping the lizard dead.</summary>
	void Trample( ReptileController player )
	{
		var velocity = player.Velocity;
		if ( velocity.LengthSquared < TrampleSpeed * TrampleSpeed ) return;
		var at = player.WorldPosition;
		float reach = CellSize * 0.5f + 120f;

		foreach ( var cell in _cells )
		{
			if ( !cell.Awake || MathF.Abs( at.x - cell.Centre.x ) > reach || MathF.Abs( at.y - cell.Centre.y ) > reach ) continue;
			for ( int i = cell.Live.Count - 1; i >= 0; i-- )
			{
				if ( i >= cell.Live.Count ) continue;
				var prop = cell.Live[i];
				if ( !prop.IsValid() ) { cell.Live.RemoveAt( i ); continue; }
				if ( prop.Kind.Weight != PropWeight.Light || prop.Loose ) continue;

				var to = prop.WorldPosition - at;
				if ( MathF.Abs( to.z ) > 90f ) continue;
				float touch = prop.Radius * 0.7f + 26f;
				if ( to.WithZ( 0f ).LengthSquared > touch * touch ) continue;
				prop.Kick( velocity * 1.2f + Vector3.Up * 220f, TrampleDamage );
			}
		}
	}

	/// <summary>Belt and braces: anything that gets the lizard outside the world puts it back in the square.</summary>
	void KeepIn( ReptileController player )
	{
		var p = player.WorldPosition;
		float edge = HalfSize + 400f;
		bool inside = MathF.Abs( p.x ) < edge && MathF.Abs( p.y ) < edge;
		if ( inside && p.z > -12f ) return;

		// Sunk into the ground (a dive too fast for the floor, or the hole it came up through): it is
		// stood back on the road where it is, so neither it nor its camera is ever left down there.
		if ( inside && p.z > -500f ) { player.Teleport( p.WithZ( 2f ) ); return; }
		player.Teleport( PlayerSpawn, PlayerSpawnYaw );
	}

	// ---- What the parts of the town ask of it ------------------------------------------------------

	/// <summary>What a hit is worth: the damage it carries, plus something for its speed alone.</summary>
	public float Force( Vector3 velocity, float damage ) => MathF.Max( damage, 0f ) * DamageScale + velocity.Length * VelocityDamage;

	/// <summary>A camera shake that fades with distance from the lizard.</summary>
	public void ShakeAt( Vector3 at, float strength )
	{
		var player = Rampage.Player;
		float distance = player.IsValid() ? player.WorldPosition.Distance( at ) : 0f;
		float felt = strength * (1f - Math.Clamp( (distance - 1200f) / 3800f, 0f, 1f ));
		if ( felt > 0.03f ) Rampage.Shake( felt );
	}

	public void TrackLoose( Destructible prop )
	{
		if ( _loose.Contains( prop ) ) return;
		_loose.Add( prop );
		if ( _loose.Count <= MaxLoose ) return;

		// Too many in the air: the one that has been loose longest is frozen where it is.
		var oldest = _loose[0];
		_loose.RemoveAt( 0 );
		if ( oldest.IsValid() ) oldest.Settle();
	}

	public void Wake( Building building )
	{
		if ( building.Ticking ) return;
		building.Ticking = true;
		_movingBuildings.Add( building );
	}

	public void Wake( Toppler toppler )
	{
		if ( toppler.Ticking ) return;
		toppler.Ticking = true;
		_movingTopplers.Add( toppler );
	}

	/// <summary>A building or a tower is down for good.</summary>
	public void StructureFell( string landmark, string label )
	{
		Standing = Math.Max( 0, Standing - 1 );
		if ( !string.IsNullOrEmpty( landmark ) ) Rampage.Announce( $"{label}: NOW A CAR PARK", 3f );
	}

	/// <summary>A flying prop has landed on something. The blow is handed over after the physics step, not during it.</summary>
	public void PassOn( IRampageTarget target, Vector3 velocity, float damage, Vector3 at )
	{
		if ( _passOns.Count < 64 ) _passOns.Add( (target, velocity, damage, at) );
	}

	void RunPassOns()
	{
		// Blows are only ever added during the physics step, never while these are handed over.
		int count = _passOns.Count;
		if ( count == 0 ) return;
		for ( int i = 0; i < count; i++ )
		{
			var blow = _passOns[i];
			if ( blow.Target is null || (blow.Target is Component c && !c.IsValid()) || !blow.Target.Alive ) continue;
			blow.Target.Hit( blow.Velocity, blow.Damage, blow.At );
		}
		_passOns.RemoveRange( 0, Math.Min( count, _passOns.Count ) );
	}

	/// <summary>Something is about to go up: a fireball and a shockwave, after a short fuse.</summary>
	public void Boom( Vector3 at, float delay, float radius, float speed )
	{
		if ( _booms.Count < 24 ) _booms.Add( (at, Time.Now + delay, radius, speed) );
	}

	void RunBooms( float now )
	{
		for ( int i = _booms.Count - 1; i >= 0; i-- )
		{
			if ( i >= _booms.Count ) continue;
			var boom = _booms[i];
			if ( now < boom.When ) continue;
			_booms.RemoveAt( i );

			Fx.Fireball( boom.At, boom.Radius / 800f );
			TownKit.Play( "explosion", boom.At, 0.05f );
			ShakeAt( boom.At, 0.8f );
			// Everybody's shockwave: the people nearby go flying too, and so does the next pump along.
			Rampage.SendShockwave( boom.At, boom.Radius, boom.Speed );
		}
	}

	/// <summary>A shockwave from anywhere: everything of the town's inside it is thrown outward, less the further out it is.</summary>
	void OnShockwave( Vector3 centre, float radius, float speed )
	{
		if ( !_raised || radius <= 0f ) return;
		float now = Time.Now;
		var near = Rampage.Borrow();
		Rampage.TargetsNear( centre, radius, near );
		for ( int i = 0; i < near.Count; i++ )
		{
			var target = near[i];
			if ( target is not Destructible && target is not Building && target is not Toppler ) continue;

			var to = target.Centre - centre;
			float distance = to.Length;
			float falloff = Math.Clamp( 1f - distance / (radius + target.Radius), 0f, 1f );
			if ( falloff < 0.03f ) continue;

			var flat = to.WithZ( 0f );
			var away = (flat.LengthSquared > 1f ? flat.Normal : Vector3.Zero) + Vector3.Up * 0.45f;

			// The blow lands when the wave gets there (see RunBlows): a street goes over like
			// dominoes, and no one frame has to knock all of it loose.
			if ( _blows.Count >= 900 ) break;
			_blows.Add( new Blow
			{
				Target = target, Velocity = away.Normal * (speed * falloff), Damage = speed * falloff * ShockDamage, At = centre,
				When = now + distance / MathF.Max( BlowWaveSpeed, 500f ),
			} );
		}
		Rampage.Return( near );
	}

	/// <summary>
	/// Something of the town's own has come down on a target (a wall, a tower). The blow is landed
	/// with the shockwaves' (see <see cref="RunBlows"/>), after a delay if it should ripple, so a
	/// tower flattening a street is spread over a few frames.
	/// </summary>
	public void Strike( IRampageTarget target, Vector3 velocity, float damage, Vector3 at, float delay = 0f )
	{
		if ( target is null || _blows.Count >= 900 ) return;
		_blows.Add( new Blow { Target = target, Velocity = velocity, Damage = damage, At = at, When = Time.Now + delay } );
	}

	/// <summary>
	/// Lands the shockwave blows that are due. A few always land; past that, only as many as fit
	/// in the frame's budget, and the rest wait a frame (more, the longer the queue).
	/// </summary>
	void RunBlows( float now )
	{
		if ( _blows.Count == 0 ) return;
		_clock = Sandbox.Diagnostics.FastTimer.StartNew();
		float budget = BlowBudgetMs * (1f + _blows.Count / 150f);
		int landed = 0;
		for ( int i = _blows.Count - 1; i >= 0; i-- )
		{
			if ( i >= _blows.Count ) continue;
			var blow = _blows[i];
			if ( now < blow.When ) continue;

			_blows[i] = _blows[^1];
			_blows.RemoveAt( _blows.Count - 1 );
			if ( blow.Target is null || (blow.Target is Component c && !c.IsValid()) || !blow.Target.Alive ) continue;

			blow.Target.Hit( blow.Velocity, blow.Damage, blow.At );
			if ( ++landed >= 4 && _clock.ElapsedMilliSeconds >= budget ) break;
		}
	}
}