Rampage/Core/RampageCore.cs

The shared core of the Rampage post-game mode: an IRampageTarget interface, a static Rampage class holding score, tier progression, a spatial grid of hittable targets, sound lookup, banner and rider commentary queues. Also contains RampageBootstrap, the scene component that resets state, wires PopulaceMap to RampageWorld and creates the Rampage modules.

using System;
using System.Collections.Generic;

// THE RAMPAGE: the post-game. Finale done and every misfit healed, the lizard goes back up to the
// surface and gives the humans their comeuppance, slapstick only: cartoon ragdolls, flying cars,
// falling buildings, no gore. Everything here is shared by the Rampage modules (World, Weapon,
// Humans, Game), which talk only through this file. Design: playtest/patch-rampage.md.

/// <summary>Anything the weapon, a shockwave or flying debris can hit: a person, a prop, a building.</summary>
public interface IRampageTarget
{
	/// <summary>False once it is broken, flattened or already flying; hits are then ignored.</summary>
	bool Alive { get; }
	/// <summary>Where to aim at it.</summary>
	Vector3 Centre { get; }
	/// <summary>Rough size, for sweep tests.</summary>
	float Radius { get; }
	/// <summary>It has been hit: thrown with this change of velocity, and hurt this much.</summary>
	void Hit( Vector3 velocity, float damage, Vector3 at );
}

/// <summary>The live rampage: shared state and noticeboard. Reset when the surface scene starts.</summary>
public static class Rampage
{
	public static ReptileController Player { get; set; }
	public static bool Running { get; set; }
	/// <summary>
	/// True once the intro is over and the lizard has control. Until then nothing scores and nobody
	/// can take hold of the lizard: the rampage does not start itself behind a black screen.
	/// </summary>
	public static bool Started { get; set; }

	// ---- Scores ----
	/// <summary>Terror, 0 to 1 within the current tier. Fills from destruction and from frightening people.</summary>
	public static float Terror { get; private set; }
	/// <summary>Total destruction caused, in points.</summary>
	public static float Destruction { get; private set; }
	/// <summary>The escalation tier, from 0. Each tier makes the weapon bigger and the response of the town sillier.</summary>
	public static int Tier { get; private set; }
	public static int HumansSent { get; private set; }
	public static int ThingsSmashed { get; private set; }

	/// <summary>Points of destruction needed to finish each tier (after the last, it keeps growing).</summary>
	/// <remarks>Written for the giant: a whip is a row of cars and a mega-swing is a block, so each tier is a few streets' worth.</remarks>
	public static readonly float[] TierNeeds = { 1000f, 2600f, 6000f, 12000f, 24000f, 48000f };
	public static readonly string[] TierNames =
	{
		"A NUISANCE", "A MENACE", "A PUBLIC INDECENCY", "AN ACT OF GOD", "A GEOLOGICAL EVENT", "THE COMEUPPANCE", "BEYOND INSURANCE",
	};
	public static string TierName => TierNames[Math.Min( Tier, TierNames.Length - 1 )];
	public static float TierNeed( int tier ) => tier < TierNeeds.Length ? TierNeeds[tier] : TierNeeds[^1] * MathF.Pow( 2.2f, tier - TierNeeds.Length + 1 );

	/// <summary>How big the weapon is: 1 at the start, growing with every tier and a little within one.</summary>
	public static float WeaponScale => 1f + Tier * 0.9f + Terror * 0.6f;

	/// <summary>
	/// How hard the weapon hits against the start: 1 at tier 0 and growing by <see cref="MightPerTier"/>
	/// with every tier (rising within one as terror fills). The town's health is written for 1 and
	/// for a giant: at tier 0 a whip flattens a row of cars, the flail takes a house and a full
	/// mega-swing takes a block.
	/// </summary>
	public static float Might => MathF.Pow( MightPerTier, Math.Min( Tier, 14 ) + Terror * 0.8f );
	/// <summary>How many times harder everything hits with each tier.</summary>
	public const float MightPerTier = 1.7f;

	static float _tierProgress;
	/// <summary>More than any one thing can be worth: a score past this is a mistake, and is not counted.</summary>
	const float MaxPoints = 1e9f;

	// ---- Events ----
	/// <summary>Something was smashed or sent flying: where, how many points, and a short label ("MAILBOX", "TAX OFFICE").</summary>
	public static event Action<Vector3, float, string> Scored;
	/// <summary>The tier went up.</summary>
	public static event Action<int> TierUp;
	/// <summary>A shockwave: centre, radius, outward speed at the centre. World and Humans react to it themselves.</summary>
	public static event Action<Vector3, float, float> Shockwave;
	/// <summary>A big moment worth a camera shake: strength 0 to 1.</summary>
	public static event Action<float> Impact;

	/// <summary>Adds destruction points. <paramref name="human"/> for a person sent flying, otherwise a thing smashed.</summary>
	public static void Score( Vector3 at, float points, string label, bool human = false )
	{
		// Points that are not a sane number (nothing, not a number, without end) are not points.
		if ( !Running || !Started || !(points > 0f) || !(points < MaxPoints) ) return;
		Destruction += points;
		if ( human ) HumansSent++; else ThingsSmashed++;
		_tierProgress += points;

		// One score can carry it up several tiers, but never round and round for ever.
		float need = TierNeed( Tier );
		for ( int climbed = 0; climbed < 32 && need > 0f && _tierProgress >= need; climbed++ )
		{
			_tierProgress -= need;
			Tier++;
			need = TierNeed( Tier );
			TierUp?.Invoke( Tier );
		}
		if ( !(need > 0f) ) need = 1f;
		Terror = Math.Clamp( _tierProgress / need, 0f, 1f );
		Scored?.Invoke( at, points, label );
	}

	public static void SendShockwave( Vector3 centre, float radius, float speed )
	{
		if ( !Running ) return;
		Shockwave?.Invoke( centre, radius, speed );
		Impact?.Invoke( Math.Clamp( radius / 1200f, 0.2f, 1f ) );
	}

	public static void Shake( float strength ) => Impact?.Invoke( Math.Clamp( strength, 0f, 1f ) );

	// ---- Targets ----
	// Thousands of things can be hit, and the weapon asks what is near it every physics step, so
	// they are kept in a grid of squares. Small things sit in the square their centre is in: ones
	// that never move are put there once, ones that do (people, loose props) are moved once a
	// frame by Tick. Big things (buildings, towers, sleeping crowds) are few and are simply looked
	// through. A query touches the few squares round it instead of everything in town.

	const float GridCell = 500f;
	/// <summary>Anything with a bigger radius than this is kept on the short list of big things.</summary>
	const float SmallRadius = 150f;
	/// <summary>How far a moving target may travel between two Ticks and still be found.</summary>
	const float GridSlack = 120f;
	/// <summary>No query is about a place further out, or wider, than this (many times the size of the world).</summary>
	const float MaxSpan = 200000f;

	sealed class Entry
	{
		public IRampageTarget Target;
		public List<Entry> Bucket;
		public long Key;
		public int Index, Slot, MovingSlot = -1;
		public bool Large;
	}

	// Sized for the whole town from the start, so nothing regrows in the middle of a street waking.
	static readonly List<IRampageTarget> _targets = new( 4096 );
	static readonly List<Entry> _entries = new( 4096 );
	static readonly Dictionary<IRampageTarget, Entry> _lookup = new( 4096 );
	static readonly Dictionary<long, List<Entry>> _grid = new( 1024 );
	static readonly List<Entry> _large = new( 256 );
	static readonly List<Entry> _moving = new( 1024 );
	static readonly List<IRampageTarget> _gone = new();
	static readonly Stack<List<IRampageTarget>> _spare = new();
	static readonly Stack<Entry> _spareEntries = new();

	public static IReadOnlyList<IRampageTarget> Targets => _targets;

	static long KeyOf( int x, int y ) => ((long)x << 32) ^ (uint)y;
	static int CellOf( float v ) => (int)MathF.Floor( v / GridCell );

	/// <summary>
	/// Adds something that can be hit. Say <paramref name="moves"/> false for a thing that stays
	/// where it is (a parked car, until it is knocked loose: then call <see cref="SetMoving"/>).
	/// </summary>
	public static void Register( IRampageTarget target, bool moves = true )
	{
		if ( target is null || _lookup.ContainsKey( target ) ) return;
		// People come and go as their blocks wake and sleep: their entries are used again.
		var entry = _spareEntries.Count > 0 ? _spareEntries.Pop() : new Entry();
		entry.Target = target;
		entry.Index = _targets.Count;
		entry.Large = target.Radius > SmallRadius;
		entry.MovingSlot = -1;
		entry.Bucket = null;
		_targets.Add( target );
		_entries.Add( entry );
		_lookup[target] = entry;

		if ( entry.Large ) { entry.Slot = _large.Count; _large.Add( entry ); return; }
		Place( entry, target.Centre );
		if ( moves ) { entry.MovingSlot = _moving.Count; _moving.Add( entry ); }
	}

	public static void Unregister( IRampageTarget target )
	{
		if ( target is null || !_lookup.TryGetValue( target, out var entry ) ) return;
		_lookup.Remove( target );

		// The lists are only touched if this entry is where it says it is: they can have been
		// emptied or shuffled under it (a hotload does it), and must never be indexed past the end.
		int last = _targets.Count - 1;
		if ( last >= 0 && _entries.Count == _targets.Count && (uint)entry.Index <= (uint)last && ReferenceEquals( _entries[entry.Index], entry ) )
		{
			if ( entry.Index != last )
			{
				_targets[entry.Index] = _targets[last];
				_entries[entry.Index] = _entries[last];
				_entries[entry.Index].Index = entry.Index;
			}
			_targets.RemoveAt( last );
			_entries.RemoveAt( last );
		}

		if ( entry.Large ) TakeFrom( _large, entry );
		else
		{
			TakeFrom( entry.Bucket, entry );
			entry.Bucket = null;
			StopMoving( entry );
		}
		entry.Target = null;
		if ( _spareEntries.Count < 2048 ) _spareEntries.Push( entry );
	}

	/// <summary>A registered target has started to move about (true) or has come to rest (false).</summary>
	public static void SetMoving( IRampageTarget target, bool moves )
	{
		if ( target is null || !_lookup.TryGetValue( target, out var entry ) || entry.Large ) return;
		if ( moves )
		{
			if ( entry.MovingSlot < 0 ) { entry.MovingSlot = _moving.Count; _moving.Add( entry ); }
			return;
		}
		StopMoving( entry );
		Move( entry, target.Centre );
	}

	static void StopMoving( Entry entry )
	{
		int slot = entry.MovingSlot;
		entry.MovingSlot = -1;
		int last = _moving.Count - 1;
		if ( slot < 0 || slot > last || !ReferenceEquals( _moving[slot], entry ) ) return;
		_moving[slot] = _moving[last];
		_moving[slot].MovingSlot = slot;
		_moving.RemoveAt( last );
		entry.MovingSlot = -1;
	}

	static void TakeFrom( List<Entry> list, Entry entry )
	{
		if ( list is null ) return;
		int last = list.Count - 1;
		if ( entry.Slot < 0 || entry.Slot > last || !ReferenceEquals( list[entry.Slot], entry ) ) return;
		list[entry.Slot] = list[last];
		list[entry.Slot].Slot = entry.Slot;
		list.RemoveAt( last );
	}

	static void Place( Entry entry, Vector3 at )
	{
		long key = KeyOf( CellOf( at.x ), CellOf( at.y ) );
		if ( !_grid.TryGetValue( key, out var bucket ) ) _grid[key] = bucket = new List<Entry>( 32 );
		entry.Key = key;
		entry.Bucket = bucket;
		entry.Slot = bucket.Count;
		bucket.Add( entry );
	}

	static void Move( Entry entry, Vector3 at )
	{
		long key = KeyOf( CellOf( at.x ), CellOf( at.y ) );
		if ( key == entry.Key && entry.Bucket is not null ) return;
		TakeFrom( entry.Bucket, entry );
		Place( entry, at );
	}

	/// <summary>Every live target within a radius of a point (each target adds its own radius). A new list each time: fine for a test, not for a frame.</summary>
	public static List<IRampageTarget> TargetsNear( Vector3 point, float radius )
	{
		var found = new List<IRampageTarget>();
		TargetsNear( point, radius, found );
		return found;
	}

	/// <summary>
	/// The same into a list of the caller's (emptied first), so nothing is made. Hitting what is
	/// found can remove targets, which is safe: the list is a copy. Take a list with
	/// <see cref="Borrow"/> and give it back with <see cref="Return"/>.
	/// </summary>
	public static void TargetsNear( Vector3 point, float radius, List<IRampageTarget> found )
	{
		found.Clear();
		_gone.Clear();

		for ( int i = 0; i < _large.Count; i++ ) Consider( _large[i].Target, point, radius, found );

		// The squares to look in. Anything that is not a sane place and size (a point or a radius
		// that is not a number, is infinite, or is out past the edge of anything) is answered by
		// looking through every square instead: a loop over squares must never be asked to count
		// to the end of the integers.
		float span = radius + SmallRadius + GridSlack;
		bool everywhere = !(span >= 0f && span < MaxSpan) || !(MathF.Abs( point.x ) < MaxSpan) || !(MathF.Abs( point.y ) < MaxSpan);
		int x0 = 0, y0 = 0, across = 0, along = 0;
		if ( !everywhere )
		{
			x0 = CellOf( point.x - span );
			y0 = CellOf( point.y - span );
			across = CellOf( point.x + span ) - x0 + 1;
			along = CellOf( point.y + span ) - y0 + 1;
			everywhere = across <= 0 || along <= 0 || (long)across * along >= _grid.Count;
		}

		if ( everywhere )
		{
			foreach ( var bucket in _grid.Values )
				for ( int i = 0; i < bucket.Count; i++ ) Consider( bucket[i].Target, point, radius, found );
		}
		else
		{
			for ( int ix = 0; ix < across; ix++ )
				for ( int iy = 0; iy < along; iy++ )
				{
					if ( !_grid.TryGetValue( KeyOf( x0 + ix, y0 + iy ), out var bucket ) ) continue;
					for ( int i = 0; i < bucket.Count; i++ ) Consider( bucket[i].Target, point, radius, found );
				}
		}

		// Anything destroyed without saying so is forgotten here.
		for ( int i = 0; i < _gone.Count; i++ ) Unregister( _gone[i] );
		_gone.Clear();
	}

	static void Consider( IRampageTarget target, Vector3 point, float radius, List<IRampageTarget> found )
	{
		if ( target is Component component && !component.IsValid() ) { _gone.Add( target ); return; }
		if ( !target.Alive ) return;
		float reach = radius + target.Radius;
		if ( (target.Centre - point).LengthSquared <= reach * reach ) found.Add( target );
	}

	/// <summary>A scratch list for the non-allocating TargetsNear. Give it back with <see cref="Return"/>.</summary>
	public static List<IRampageTarget> Borrow() => _spare.Count > 0 ? _spare.Pop() : new List<IRampageTarget>( 64 );

	public static void Return( List<IRampageTarget> list )
	{
		if ( list is null ) return;
		list.Clear();
		if ( _spare.Count < 16 ) _spare.Push( list );
	}

	// ---- Sounds ----
	// Every Rampage sound is sounds/rampage/<name>.sound. Each name is looked up once; a sound
	// that does not exist is remembered as silent, so nothing is ever tried (or thrown) twice.

	sealed class SoundSlot { public SoundEvent Event; public string Path; public bool Silent; }
	static readonly Dictionary<string, SoundSlot> _sounds = new();

	static SoundSlot SlotFor( string name )
	{
		if ( _sounds.TryGetValue( name, out var slot ) ) return slot;
		slot = new SoundSlot { Path = "sounds/rampage/" + name + ".sound" };
		if ( ResourceLibrary.TryGet<SoundEvent>( slot.Path, out var found ) ) slot.Event = found;
		_sounds[name] = slot;
		return slot;
	}

	/// <summary>Plays a Rampage sound at a place, by its short name. Null if there is no such sound.</summary>
	public static SoundHandle PlaySound( string name, Vector3 at )
	{
		if ( string.IsNullOrEmpty( name ) ) return null;
		var slot = SlotFor( name );
		if ( slot.Silent ) return null;
		SoundHandle handle;
		if ( slot.Event is not null ) handle = Sound.Play( slot.Event, at );
		else
		{
			// Not in the library (made since the editor started, perhaps): by path, and if even that
			// fails it is left alone from now on.
			try { handle = Sound.Play( slot.Path, at ); }
			catch ( Exception ) { slot.Silent = true; return null; }
		}
		return handle.IsValid() ? handle : null;
	}

	/// <summary>Plays a Rampage sound with no position (music, stingers). Null if there is no such sound.</summary>
	public static SoundHandle PlaySound( string name )
	{
		if ( string.IsNullOrEmpty( name ) ) return null;
		var slot = SlotFor( name );
		if ( slot.Silent ) return null;
		SoundHandle handle;
		if ( slot.Event is not null ) handle = Sound.Play( slot.Event );
		else
		{
			try { handle = Sound.Play( slot.Path ); }
			catch ( Exception ) { slot.Silent = true; return null; }
		}
		return handle.IsValid() ? handle : null;
	}

	// ---- For the HUD ----
	public static string Prompt { get; set; }
	/// <summary>The announcement showing now, and when it comes down (real time).</summary>
	public static string Banner { get; private set; } = "";
	public static float BannerUntil { get; private set; }

	/// <summary>Every module announces through here, so they are queued: each gets at least this long before the next.</summary>
	const float BannerMinSeconds = 1.25f;
	/// <summary>An announcement still waiting after this long is old news and is dropped.</summary>
	const float BannerStaleSeconds = 7f;

	sealed class Waiting { public string Text; public float Seconds, Asked; }
	static readonly List<Waiting> _banners = new();
	static float _bannerSince, _bannerHold;

	/// <summary>Puts a line on the banner. If one is up already this one waits its turn (the same line is never queued twice).</summary>
	public static void Announce( string text, float seconds = 3f )
	{
		if ( string.IsNullOrEmpty( text ) ) return;
		float now = RealTime.Now;
		if ( now < BannerUntil && Banner == text )
		{
			BannerUntil = MathF.Max( BannerUntil, now + MathF.Min( seconds, 1.5f ) );
			return;
		}
		for ( int i = 0; i < _banners.Count; i++ )
			if ( _banners[i].Text == text ) return;
		if ( _banners.Count >= 5 ) _banners.RemoveAt( 0 );
		_banners.Add( new Waiting { Text = text, Seconds = seconds, Asked = now } );
		PumpBanners( now );
	}

	// ---- The riders' commentary ----
	// The misfits riding the giant talk through here, not through the banner: one line at a time,
	// with the speaker's name, shown by the HUD in its own strip. A line that arrives while another
	// is still fresh is simply dropped (it is seasoning), unless it is marked urgent.

	public static string RiderName { get; private set; } = "";
	public static string RiderLine { get; private set; } = "";
	/// <summary>When the line showing comes down (real time).</summary>
	public static float RiderLineUntil { get; private set; }
	static float _riderQuietUntil, _riderShownAt;

	/// <summary>A rider says something. False if it was not shown (somebody else is still talking).</summary>
	public static bool RiderSay( string speaker, string line, float seconds = 3.2f, float quietAfter = 2.5f, bool urgent = false )
	{
		if ( !Running || string.IsNullOrEmpty( line ) ) return false;
		float now = RealTime.Now;
		if ( !urgent && now < _riderQuietUntil ) return false;
		// An urgent line (their own landmark, being knocked off) may cut in, but not on a line that has only just gone up.
		if ( urgent && now < RiderLineUntil && now < _riderShownAt + 1.2f ) return false;
		_riderShownAt = now;
		RiderName = speaker ?? "";
		RiderLine = line;
		RiderLineUntil = now + seconds;
		_riderQuietUntil = now + seconds + MathF.Max( quietAfter, 0f );
		return true;
	}

	/// <summary>Nothing new goes on the banner for this long (the tier stamp has the screen).</summary>
	public static void HoldBanners( float seconds ) => _bannerHold = MathF.Max( _bannerHold, RealTime.Now + seconds );

	static void PumpBanners( float now )
	{
		if ( _banners.Count == 0 || now < _bannerHold ) return;

		// The one that is up keeps its full time unless somebody is waiting, and then at least a moment.
		bool showing = now < BannerUntil && !string.IsNullOrEmpty( Banner );
		if ( showing && now < _bannerSince + BannerMinSeconds ) return;

		while ( _banners.Count > 0 )
		{
			var next = _banners[0];
			_banners.RemoveAt( 0 );
			if ( now - next.Asked > BannerStaleSeconds ) continue;
			Banner = next.Text;
			_bannerSince = now;
			BannerUntil = now + MathF.Max( next.Seconds, BannerMinSeconds );
			return;
		}
	}

	/// <summary>Once a frame, from <see cref="RampageBootstrap"/>: moving targets are put in their squares and the banner moves on.</summary>
	public static void Tick()
	{
		for ( int i = _moving.Count - 1; i >= 0; i-- )
		{
			if ( i >= _moving.Count ) continue;
			var entry = _moving[i];
			if ( entry?.Target is null ) { _moving.RemoveAt( i ); continue; }
			if ( entry.Target is Component component && !component.IsValid() ) { Unregister( entry.Target ); continue; }
			Move( entry, entry.Target.Centre );
		}
		PumpBanners( RealTime.Now );
	}

	/// <summary>True once the post-game is earned: the finale is done and everyone is healed.</summary>
	public static bool Unlocked
	{
		get
		{
			SumpState.EnsureStarted();
			return SumpState.FinaleDone && SumpState.HealedCount >= SumpState.MisfitCount;
		}
	}

	public const string ScenePath = "scenes/surface.scene";

	public static void ResetScene()
	{
		Player = null;
		Running = false;
		Started = false;
		Terror = 0f; Destruction = 0f; Tier = 0; HumansSent = 0; ThingsSmashed = 0; _tierProgress = 0f;
		Prompt = null; Banner = ""; BannerUntil = 0f;
		_banners.Clear(); _bannerSince = 0f; _bannerHold = 0f;
		RiderName = ""; RiderLine = ""; RiderLineUntil = 0f; _riderQuietUntil = 0f; _riderShownAt = 0f;
		_targets.Clear(); _entries.Clear(); _lookup.Clear(); _large.Clear(); _moving.Clear(); _gone.Clear();
		foreach ( var bucket in _grid.Values ) bucket.Clear();      // the squares are kept, empty, for the next run
		_sounds.Clear();
		Scored = null; TierUp = null; Shockwave = null; Impact = null;
	}
}

/// <summary>
/// The one component placed in scenes/surface.scene. Starts every Rampage module when the scene
/// starts, on this object or on the player.
/// </summary>
[Title( "Rampage Bootstrap" ), Category( "Rampage" ), Icon( "local_fire_department" )]
public sealed class RampageBootstrap : Component
{
	public static RampageBootstrap Current { get; private set; }

	protected override void OnAwake()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		Rampage.ResetScene();

		// The humans stand and flee where the town says the streets are.
		PopulaceMap.Reset();
		PopulaceMap.Ready = () => RampageWorld.Ready;
		PopulaceMap.StreetPoints = () => RampageWorld.StreetPoints;
		PopulaceMap.GroundHeight = RampageWorld.GroundHeightAt;
		PopulaceMap.HalfSize = RampageWorld.HalfSize;
		PopulaceMap.Centre = Vector3.Zero;
		PopulaceMap.Landmarks = () => RampageWorld.Landmarks;
		PopulaceMap.LandmarkNames = () => RampageWorld.LandmarkNames;
		PopulaceMap.Walkable = RampageWorld.IsStreet;
		PopulaceMap.Cover = () => RampageWorld.CoverPoints;
	}

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Current = this;

		ReptileController player = null;
		foreach ( var found in Scene.GetAllComponents<ReptileController>() ) { player = found; break; }
		Rampage.Player = player;
		if ( player.IsValid() )
		{
			player.UseNewModel = true;      // the weapon lives on the rigged model
			player.StayInCaves = false;
		}
		if ( Scene.Camera.IsValid() ) Scene.Camera.ZFar = 60000f;

		Components.GetOrCreate<RampageWorld>();
		Components.GetOrCreate<RampagePopulace>();
		Components.GetOrCreate<RampageGame>();
		if ( player.IsValid() )
		{
			// The giant first: the weapon, the riders and the town's heavier answers all take their size from it.
			player.Components.GetOrCreate<RampageGiant>();
			player.Components.GetOrCreate<DongWeapon>();
			player.Components.GetOrCreate<GiantRiders>();
			Components.GetOrCreate<GiantFoes>();
		}
		Rampage.Running = true;
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || Current != this ) return;
		// With no game component to run an intro, it has started as soon as it is running.
		if ( Rampage.Running && !Rampage.Started && !RampageGame.Current.IsValid() ) Rampage.Started = true;
		Rampage.Tick();
	}

	protected override void OnDestroy()
	{
		if ( Current != this ) return;
		Current = null;
		Rampage.Running = false;

		// Whatever state the modules were in, the lizard never leaves here locked, leashed or slowed.
		var player = Rampage.Player;
		if ( player.IsValid() )
		{
			player.InputLocked = false;
			player.LookLocked = false;
			player.Leash = null;
			player.ClearView = false;
			player.SetSpeedFactor( "weapon", 1f );
			player.SetSpeedFactor( "grips", 1f );
			player.SetSpeedFactor( "giant", 1f );
		}
	}
}