Sump/Flashbacks/LabFlashback.cs

A flashback escape mission built on the Flashback base class. Constructs a facility out of Arena slabs (theatre, corridors, office, plant room, loading dock), straps the player to a table on a timer, and drives the breakout: strap-breaking by crowd shake force, a cycling theatre door, Watcher staff that see and chase, a keycard door, a breaker that cuts the power and opens every door, and a capture loop that wheels the player back to the table with less time left.

using System;
using System.Collections.Generic;

/// <summary>
/// LAB ESCAPE: an escape game against a clock. A white facility of corridors. You wake strapped
/// to the table in the operating theatre with a countdown to "the procedure". Break the straps
/// (the shake-free mechanic: shake the mouse, hammer SPACE), slip out when the theatre door
/// cycles (or through the vent), keep away from the orderlies, take a keycard from the office,
/// cut the power in the plant room (the lights go red and every door fails open), and get out
/// through the loading dock. Orderlies who pin you wheel you back to the table and strap you
/// down again, with less time on the clock. Each alarm state brings more of them.
/// </summary>
public sealed class LabFlashback : Flashback
{
	// ---- Tuning ---------------------------------------------------------------------------------
	/// <summary>Seconds until the procedure, from waking up.</summary>
	const float ProcedureSeconds = 230f;
	/// <summary>Force needed on a strap (the crowd's shake force) and how fast one gives.</summary>
	const float StrapForce = 4600f, StrapRate = 2.6f;
	const int StrapsAtStart = 3, StrapsAfterCapture = 2;
	/// <summary>Seconds pinned by orderlies before they wheel you back, and what it costs on the clock.</summary>
	const float WheelBackAfter = 3.5f, WheelBackPenalty = 18f;
	/// <summary>The theatre door: seconds shut, then seconds open.</summary>
	const float DoorShutSeconds = 6.5f, DoorOpenSeconds = 3.4f;
	/// <summary>Off the table this long and somebody notices, seen or not.</summary>
	const float MissedAfter = 45f;
	const float GiveUpSeconds = 8f;
	const float TakeRadius = 60f;

	const float H = 150f;          // ceiling height
	const float DoorHeight = 104f;
	const float VentHeight = 32f;

	static readonly Color Wall = new( 0.88f, 0.9f, 0.92f );
	static readonly Color Floor = new( 0.7f, 0.74f, 0.76f );
	static readonly Color Steel = new( 0.55f, 0.6f, 0.65f );

	public override string GenreTitle => "LAB ESCAPE";

	// ---- State ----------------------------------------------------------------------------------
	readonly List<Watcher> _staff = new();      // everyone with eyes
	readonly List<Watcher> _reserve = new();    // those who only come out when the alarm goes up
	readonly List<PointLight> _lamps = new();
	readonly List<GameObject> _strapObjects = new();
	GameObject _theatreDoor, _cardDoor, _securityDoor, _doorLight, _keycard, _keepsake, _breaker, _alarmSign;
	Vector3 _keycardAt, _keepsakeAt, _fatGuyAt;
	static readonly Vector3 Table = new( 0f, 0f, 36f );
	static readonly Vector3 Breaker = new( 800f, -700f, 0f );

	int _straps, _alarm;
	float _strain, _offTableFor, _blackUntil, _seenFor, _nextIntercom;
	bool _doorOpen, _hasCard, _powerCut, _escaped, _keepsakeTaken, _techSpoke, _leftTheatre, _cardDoorOpen;
	float _mirrorFatGuy;

	// ---- Building -------------------------------------------------------------------------------

	public override void Build()
	{
		var a = Arena;
		string[] sites = { "Facility 9, Nevada", "the Halvorsen Institute, sub-level 3", "an Air Force annex, New Mexico", "Site Lambda, under a dairy in Wisconsin", "Building 14, Fort Carrow" };
		Place = $"{Pick( sites )}. {Rng.Next( 1953, 1994 )}";

		a.Crowd.Centre = a.P( 900f, 0f );
		a.Crowd.HalfX = 1300f;
		a.Crowd.HalfY = 940f;
		a.Air( new Color( 0.42f, 0.45f, 0.48f ), new Color( 0.8f, 0.85f, 0.9f ), 3000f, 12000f );

		_mirrorFatGuy = Rng.Next( 2 ) == 0 ? 1f : -1f;
		_fatGuyAt = new Vector3( 392f, 400f * _mirrorFatGuy, 0f );

		BuildShell();
		BuildTheatre();
		BuildRooms();
		BuildDock();
		BuildPeople();

		Start = a.P( Table );
		StartYaw = a.Yaw( 0f );

		var rules = Rules;
		rules.TimeLimit = ProcedureSeconds;
		rules.TimeLabel = "THE PROCEDURE BEGINS IN";
		rules.TimeUpLine = "The procedure began on time.";
		rules.RewindGrace = 110f * a.Body.Patience;   // a rewind always leaves time to get out
		rules.PinLoseSeconds = 0f;       // pinned here means wheeled back, not lost
		rules.BoundsRadius = 3600f;
		rules.Won = () => _escaped;
	}

	// A wall along X at one Y, and along Y at one X (16 thick, floor to ceiling).
	void WallX( float y, float x0, float x1 ) => Arena.Slab( "Wall", x0, x1, y - 8f, y + 8f, 0f, H, Wall );
	void WallY( float x, float y0, float y1 ) => Arena.Slab( "Wall", x - 8f, x + 8f, y0, y1, 0f, H, Wall );
	// The piece of wall over a doorway or a vent.
	void LintelX( float y, float x0, float x1, float from ) => Arena.Slab( "Lintel", x0, x1, y - 8f, y + 8f, from, H, Wall );
	void LintelY( float x, float y0, float y1, float from ) => Arena.Slab( "Lintel", x - 8f, x + 8f, y0, y1, from, H, Wall );

	void RoomLight( float x, float y, float radius = 620f )
	{
		_lamps.Add( Arena.Lamp( "Strip Light", new Vector3( x, y, H - 14f ), Color.White, radius, 0.9f ) );
		Arena.Slab( "Strip Light Tube", x - 30f, x + 30f, y - 5f, y + 5f, H - 4f, H - 1f, Color.White, false, null, false );
	}

	/// <summary>Floor, ceiling and every wall. See the plan in the comments: X runs from the theatre (west) to the dock (east).</summary>
	void BuildShell()
	{
		var a = Arena;
		a.Slab( "Floor", -280f, 2200f, -930f, 930f, -40f, 0f, Floor );
		a.Slab( "Ceiling", -280f, 2200f, -930f, 930f, H, H + 16f, new Color( 0.8f, 0.82f, 0.84f ), true, null, false );

		// Theatre (x -250..250, y -250..250), with the observation room north of it.
		WallY( -250f, -250f, 430f );
		WallX( -250f, -250f, 250f );
		WallX( 250f, -250f, -150f );
		WallX( 250f, 150f, 250f );
		a.Slab( "Window Sill", -150f, 150f, 242f, 258f, 0f, 50f, Wall );
		a.Slab( "Observation Window", -150f, 150f, 247f, 253f, 50f, 118f, new Color( 0.55f, 0.75f, 0.85f ), true, null, false );
		LintelX( 250f, -150f, 150f, 118f );
		WallX( 430f, -250f, 250f );

		// The theatre's east wall: a vent low down, then the door that cycles.
		WallY( 250f, -250f, -215f );
		LintelY( 250f, -215f, -165f, VentHeight );
		a.Slab( "Vent Frame", 240f, 260f, -219f, -215f, 0f, VentHeight + 4f, Steel, false, null, false );
		a.Slab( "Vent Frame", 240f, 260f, -165f, -161f, 0f, VentHeight + 4f, Steel, false, null, false );
		WallY( 250f, -165f, -45f );
		LintelY( 250f, -45f, 45f, DoorHeight );
		WallY( 250f, 45f, 250f );

		// Corridor 1, north to south (x 250..450, y -900..900).
		WallY( 250f, -900f, -250f );
		WallY( 250f, 250f, 900f );
		WallX( -900f, 250f, 450f );
		WallX( 900f, 250f, 450f );
		// Its east wall: plant room door (keycard), the mouth of corridor 2, the office door.
		WallY( 450f, -900f, -750f );
		LintelY( 450f, -750f, -650f, DoorHeight );
		WallY( 450f, -650f, -100f );
		WallY( 450f, 100f, 650f );
		LintelY( 450f, 650f, 750f, DoorHeight );
		WallY( 450f, 750f, 900f );

		// Office (north-east) and plant room (south-east).
		WallX( 900f, 450f, 850f );
		WallX( 500f, 450f, 1000f );
		WallY( 850f, 500f, 900f );
		WallX( -900f, 450f, 850f );
		WallX( -500f, 450f, 1000f );
		WallY( 850f, -900f, -500f );

		// Corridor 2, west to east (x 450..1500, y -100..100), with the ward and the break room off it.
		WallX( 100f, 450f, 600f );
		LintelX( 100f, 600f, 700f, DoorHeight );
		WallX( 100f, 700f, 1500f );
		WallX( -100f, 450f, 850f );
		LintelX( -100f, 850f, 950f, DoorHeight );
		WallX( -100f, 950f, 1500f );
		WallY( 1000f, 100f, 500f );
		WallY( 1000f, -500f, -100f );

		// Loading dock (x 1500..2100, y -400..400): its shutter stands open on daylight.
		WallY( 1500f, -400f, -100f );
		WallY( 1500f, 100f, 400f );
		WallX( 400f, 1500f, 2100f );
		WallX( -400f, 1500f, 2100f );
		WallY( 2100f, -400f, -160f );
		WallY( 2100f, 160f, 400f );
		LintelY( 2100f, -160f, 160f, 128f );
		a.Slab( "Daylight", 2190f, 2196f, -400f, 400f, 0f, H, new Color( 1f, 1f, 0.95f ), true, null, false );
		a.Slab( "Yard", 2100f, 2200f, -400f, 400f, 0f, 1f, new Color( 0.5f, 0.5f, 0.48f ), false, null, false );
		a.Barrier( "Yard Side", 2100f, 2200f, 160f, 176f, 0f, H );
		a.Barrier( "Yard Side", 2100f, 2200f, -176f, -160f, 0f, H );
		a.Lamp( "Daylight Glow", new Vector3( 2150f, 0f, 90f ), new Color( 1f, 0.97f, 0.88f ), 900f, 2.2f );

		// Lights down every room and corridor.
		for ( float y = -750f; y <= 750f; y += 300f ) RoomLight( 350f, y, 520f );
		for ( float x = 600f; x <= 1400f; x += 266f ) RoomLight( x, 0f, 480f );
		RoomLight( 650f, 700f ); RoomLight( 650f, -700f ); RoomLight( 725f, 300f ); RoomLight( 725f, -300f );
		RoomLight( 0f, 340f, 420f ); RoomLight( 1800f, 0f, 800f );
	}

	void BuildTheatre()
	{
		var a = Arena;
		a.Slab( "Table", -46f, 46f, -22f, 22f, 0f, 30f, Steel );
		a.Slab( "Table Pad", -44f, 44f, -20f, 20f, 30f, 35f, new Color( 0.3f, 0.5f, 0.45f ), true, null, false );
		a.Slab( "Instrument Tray", -30f, 30f, 70f, 100f, 0f, 34f, Steel );
		for ( int i = 0; i < 5; i++ )
			a.Block( "Instrument", new Vector3( -22f + i * 11f, 85f, 35.5f ), new Vector3( 2f, 18f, 1f ), new Color( 0.9f, 0.92f, 0.95f ), false, null, false );
		a.Slab( "Drain", -20f, 20f, -80f, -60f, 0f, 0.6f, new Color( 0.15f, 0.15f, 0.16f ), false, null, false );
		a.Spot( "Theatre Lamp", new Vector3( 0f, 0f, H - 6f ), new Vector3( 0f, 0f, 0f ), Color.White, 38f, 2.4f, true );
		a.Ball( "Theatre Lamp Head", new Vector3( 0f, 0f, H - 8f ), new Vector3( 26f, 26f, 8f ), Steel );
		_lamps.Add( a.Lamp( "Theatre Fill", new Vector3( -150f, -150f, H - 20f ), Color.White, 520f, 0.5f ) );

		// The door that cycles, with a light over it: red shut, green open.
		_theatreDoor = a.Slab( "Theatre Door", 244f, 256f, -45f, 45f, 0f, DoorHeight, new Color( 0.35f, 0.45f, 0.55f ) );
		_doorLight = a.Slab( "Door Light", 236f, 242f, -12f, 12f, DoorHeight + 6f, DoorHeight + 14f, Color.Red, false, null, false );

		// Straps across the table: one goes each time you break one.
		for ( int i = 0; i < StrapsAtStart; i++ )
			_strapObjects.Add( a.Slab( "Strap", -34f + i * 28f, -26f + i * 28f, -24f, 24f, 35f, 56f, new Color( 0.35f, 0.25f, 0.15f ), false, null, false ) );
	}

	void BuildRooms()
	{
		var a = Arena;

		// Office: desks, and a keycard somebody has left lying about (where, depends on the misfit).
		a.Slab( "Desk", 640f, 780f, 800f, 850f, 0f, 32f, new Color( 0.5f, 0.4f, 0.3f ) );
		a.Slab( "Desk", 760f, 820f, 560f, 660f, 0f, 32f, new Color( 0.5f, 0.4f, 0.3f ) );
		a.Slab( "Filing Cabinet", 500f, 540f, 840f, 880f, 0f, 70f, Steel );
		Vector3[] cardSpots = { new( 700f, 760f, 0f ), new( 720f, 620f, 0f ), new( 560f, 820f, 0f ) };
		_keycardAt = Pick( cardSpots );
		_keycard = a.Pickup( "Keycard", _keycardAt, new Color( 1f, 0.85f, 0.2f ) );

		// Plant room: the breaker on the far wall, behind the keycard door.
		_cardDoor = a.Slab( "Plant Room Door", 444f, 456f, -750f, -650f, 0f, DoorHeight, new Color( 0.85f, 0.7f, 0.15f ) );
		a.Slab( "Card Reader", 438f, 444f, -640f, -628f, 44f, 60f, new Color( 0.1f, 0.1f, 0.12f ), false, null, false );
		a.Slab( "Generator", 520f, 700f, -880f, -800f, 0f, 90f, new Color( 0.3f, 0.34f, 0.3f ) );
		a.Slab( "Breaker Cabinet", 826f, 842f, -750f, -650f, 20f, 120f, new Color( 0.4f, 0.42f, 0.44f ) );
		_breaker = a.Slab( "Breaker Lever", 818f, 826f, -706f, -694f, 70f, 100f, new Color( 0.9f, 0.15f, 0.1f ), false, null, false );
		a.Lamp( "Breaker Light", new Vector3( 800f, -700f, 110f ), new Color( 1f, 0.3f, 0.2f ), 220f, 0.8f );

		// Corridor 2's security door: shut until the power goes.
		_securityDoor = a.Slab( "Security Door", 1144f, 1156f, -92f, 92f, 0f, H, new Color( 0.6f, 0.15f, 0.12f ) );
		_alarmSign = a.Sign( "", new Vector3( 1140f, 0f, 120f ), 180f, 14f, Color.Red );

		// Ward: beds. Break room: a table, cold coffee, and the thing the misfit will never put down.
		for ( int i = 0; i < 3; i++ )
		{
			a.Slab( "Bed", 520f + i * 150f, 600f + i * 150f, 400f, 480f, 0f, 26f, new Color( 0.85f, 0.87f, 0.9f ) );
			a.Slab( "Bed Rail", 520f + i * 150f, 600f + i * 150f, 478f, 482f, 26f, 44f, Steel, false, null, false );
		}
		a.Slab( "Break Table", 620f, 720f, -380f, -300f, 0f, 30f, new Color( 0.6f, 0.5f, 0.4f ) );
		a.Slab( "Vending Machine", 940f, 990f, -480f, -420f, 0f, 80f, new Color( 0.75f, 0.2f, 0.2f ) );
		_keepsakeAt = new Vector3( 760f + R( -30f, 60f ), -330f + R( -60f, 30f ), 0f );
		_keepsake = a.Keepsake( _keepsakeAt );
	}

	void BuildDock()
	{
		var a = Arena;
		a.Slab( "Dock Truck", 1700f, 1980f, 220f, 340f, 20f, 140f, new Color( 0.3f, 0.36f, 0.3f ) );
		for ( int i = 0; i < 6; i++ )
		{
			float size = R( 40f, 70f );
			var at = new Vector3( R( 1560f, 2000f ), R( -360f, -170f ), 0f );
			a.Block( "Crate", at + Vector3.Up * (size * 0.5f), new Vector3( size, size, size ), new Color( 0.55f, 0.45f, 0.3f ) );
		}
		a.Sign( "LOADING", new Vector3( 1508f, 0f, 125f ), 180f, 14f, new Color( 0.2f, 0.6f, 0.3f ) );
	}

	void BuildPeople()
	{
		var a = Arena;
		var scrubs = new HumanLook { Shirt = new Color( 0.55f, 0.75f, 0.7f ), Trousers = new Color( 0.55f, 0.75f, 0.7f ), Hat = new Color( 0.5f, 0.7f, 0.66f ), WalkSpeed = 76f, RunSpeed = 150f };
		var coat = new HumanLook { Shirt = new Color( 0.7f, 0.75f, 0.85f ), Trousers = new Color( 0.25f, 0.25f, 0.3f ), Coat = Color.White, WalkSpeed = 64f, RunSpeed = 125f };
		var guard = new HumanLook { Shirt = new Color( 0.12f, 0.14f, 0.25f ), Trousers = new Color( 0.12f, 0.14f, 0.25f ), Hat = new Color( 0.1f, 0.1f, 0.18f ), WalkSpeed = 70f, RunSpeed = 165f };

		// Orderlies on their rounds. The corridor-1 round keeps to the west side, past the man eating his lunch.
		AddStaff( _staff, "ORDERLY", new Vector3( 300f, 620f * _mirrorFatGuy, 0f ), scrubs,
			new[] { new Vector3( 300f, 150f * _mirrorFatGuy, 0f ), new Vector3( 300f, 820f * _mirrorFatGuy, 0f ) } );
		AddStaff( _staff, "ORDERLY", new Vector3( 800f, 0f, 0f ), scrubs,
			new[] { new Vector3( 560f, 0f, 0f ), new Vector3( 1080f, 0f, 0f ) } );
		if ( Rng.Next( 3 ) > 0 )
			AddStaff( _staff, "ORDERLY", new Vector3( 350f, -500f * _mirrorFatGuy, 0f ), scrubs,
				new[] { new Vector3( 350f, -200f * _mirrorFatGuy, 0f ), new Vector3( 350f, -820f * _mirrorFatGuy, 0f ) } );
		AddStaff( _staff, "DOCK GUARD", new Vector3( 1650f, -80f, 0f ), guard,
			new[] { new Vector3( 1600f, -80f, 0f ), new Vector3( 1950f, 60f, 0f ) } );

		// Scientists: two behind the glass watching you wake, one at a desk in the office.
		AddStaff( _staff, "DR. HALE", new Vector3( -70f, 330f, 0f ), coat, null, -90f );
		AddStaff( _staff, "DR. OKAFOR", new Vector3( 80f, 340f, 0f ), coat, null, -90f );
		var clerk = AddStaff( _staff, "RESEARCHER", new Vector3( 800f, 800f, 0f ), coat, null, 180f );
		clerk.Range = 300f;

		// The reserve: orderlies in the ward and the break room who only come out when the alarm goes up.
		int reserve = 2 + Rng.Next( 0, 3 );
		for ( int i = 0; i < reserve; i++ )
		{
			bool ward = i % 2 == 0;
			var at = ward ? new Vector3( 560f + i * 70f, 300f, 0f ) : new Vector3( 560f + i * 70f, -200f, 0f );
			AddStaff( _reserve, "ORDERLY", at, scrubs, null, ward ? -90f : 90f );
		}

		// The Fat Guy: a technician eating his lunch on the corridor floor, in everybody's way.
		a.FatGuyCameo( _fatGuyAt, 180f, true, new Color( 0.9f, 0.92f, 0.95f ) );
		a.Block( "Lunchbox", _fatGuyAt + new Vector3( -52f, 30f, 6f ), new Vector3( 16f, 12f, 12f ), new Color( 0.85f, 0.25f, 0.2f ), false, null, false );
	}

	Watcher AddStaff( List<Watcher> into, string name, Vector3 at, HumanLook look, Vector3[] route, float yaw = 0f )
	{
		var world = Array.Empty<Vector3>();
		if ( route is not null )
		{
			world = new Vector3[route.Length];
			for ( int i = 0; i < route.Length; i++ ) world[i] = Arena.P( route[i] );
		}

		var watcher = new Watcher
		{
			Name = name,
			Person = Arena.Human( name, at, yaw, look ),
			Post = Arena.P( at ), PostYaw = Arena.Yaw( yaw ),
			Route = world,
			Range = 560f, HalfAngle = 38f, NearRange = 90f, Pause = R( 1.5f, 3.5f ),
		};
		into.Add( watcher );
		return watcher;
	}

	// ---- Playing --------------------------------------------------------------------------------

	public override void Begin()
	{
		Strap( StrapsAtStart );
		Say( "DR. HALE", "Subject is awake. Note the time. We open it up in under four minutes. Somebody find out which end is the front." );
		Say( "DR. OKAFOR", "It was holding on to something when they brought it in. They took that off it. It made a noise." );
		_nextIntercom = Time.Now + 40f;
	}

	/// <summary>Back on the table under this many straps.</summary>
	void Strap( int straps )
	{
		var a = Arena;
		_straps = straps;
		_strain = 0f;
		_offTableFor = 0f;
		a.Crowd.Struggling = true;
		a.Player.Pin( a.P( Table ) );
		for ( int i = 0; i < _strapObjects.Count; i++ )
			if ( _strapObjects[i].IsValid() ) _strapObjects[i].Enabled = i < straps;
	}

	protected override void Tick( float dt )
	{
		var a = Arena;
		float now = Time.Now;
		var local = a.PlayerLocal;

		// A capture cuts to black for a moment.
		if ( _blackUntil > 0f )
		{
			Sump.Fade = Math.Clamp( (_blackUntil - RealTime.Now) / 0.5f, 0f, 1f );
			if ( RealTime.Now >= _blackUntil ) { _blackUntil = 0f; Sump.Fade = 0f; }
		}

		CycleDoor( now );
		if ( _straps > 0 ) { Struggle( dt ); UpdateObjective(); return; }

		a.Visibility = a.Body.Visibility * (a.PlayerSpeed < 14f ? a.Body.StillVisibility : 1f) * (_powerCut ? 0.6f : 1f);
		_offTableFor += dt;
		if ( !_leftTheatre && local.x > 262f )
		{
			_leftTheatre = true;
			Rules.Reach( "corridor", a.Player.WorldPosition, a.Player.Look.yaw, 1 );
		}

		Watch( dt, now );
		Doors( local );
		Things( local, now );

		// Pinned by orderlies: wheeled back to the table.
		if ( a.Crowd.PinnedSeconds >= WheelBackAfter ) WheelBack();

		if ( !_escaped && local.x > 2030f && MathF.Abs( local.y ) < 170f ) _escaped = true;
		UpdateObjective();
	}

	/// <summary>The straps: the same thrashing that shakes off a hand. Each one snaps in turn.</summary>
	void Struggle( float dt )
	{
		var a = Arena;
		float needed = StrapForce * MathF.Max( a.Body.Grip, 0.4f );
		float ratio = a.Crowd.ShakeForce / needed;
		_strain = ratio > 0.5f ? _strain + ratio * StrapRate * dt : MathF.Max( _strain - 0.4f * dt, 0f );
		Rules.Meter = Math.Clamp( _strain, 0f, 1f );
		Rules.MeterLabel = $"STRAP ({_straps} LEFT)";
		Sump.Prompt = "Strapped down. Shake the mouse and hammer SPACE to break the straps";
		if ( _strain < 1f ) return;

		_strain = 0f;
		_straps--;
		if ( _straps < _strapObjects.Count && _strapObjects[_straps].IsValid() ) _strapObjects[_straps].Enabled = false;
		Sump.Sfx( "lab_strap_snap", a.Player.WorldPosition );
		a.Player.Kick( Vector3.Random * 10f );
		if ( _straps > 0 ) return;

		a.Crowd.Struggling = false;
		a.Player.Unpin();
		Rules.Meter = -1f;
		Say( Who, "Loose. The door opens when the light over it goes green. There is a vent low in the wall, too." );
	}

	void CycleDoor( float now )
	{
		if ( _powerCut ) return;
		float t = now % (DoorShutSeconds + DoorOpenSeconds);
		bool open = t > DoorShutSeconds;
		if ( open == _doorOpen ) return;
		_doorOpen = open;
		if ( _theatreDoor.IsValid() ) _theatreDoor.Enabled = !open;
		Arena.Nav?.MarkDirty( _theatreDoor );
		FlashbackArena.Tint( _doorLight, open ? Color.Green : Color.Red );
		Sump.Sfx( open ? "lab_door_open" : "lab_door_close", Arena.P( 250f, 0f, 50f ) );
	}

	/// <summary>Who has seen you, and what the alarm does about it.</summary>
	void Watch( float dt, float now )
	{
		var a = Arena;
		bool anySees = false;

		foreach ( var list in new[] { _staff, _reserve } )
		{
			foreach ( var watcher in list )
			{
				// The reserve does not look about until it has been called out.
				bool active = list == _staff || _alarm >= 2;
				if ( !active ) continue;
				watcher.Update( a, dt );
				anySees |= watcher.Sees;

				if ( watcher.Sees && _alarm >= 1 && !watcher.Chasing ) watcher.Chase();
				if ( _alarm >= 3 && !watcher.Chasing && (watcher.Position - a.Player.WorldPosition).Length < 1100f ) watcher.Chase();

				// Lost you: back to the round. If they have wandered off it, they are simply back at their post
				// the next time you look (they know these corridors; they do not get stuck in them).
				if ( watcher.Chasing && _alarm < 3 && watcher.LostFor > GiveUpSeconds && !a.Crowd.Held )
				{
					if ( !a.ClearLine( watcher.Eye, a.Player.WorldPosition + Vector3.Up * 12f ) ) watcher.Reset();
				}
			}
		}

		_seenFor = anySees ? _seenFor + dt : MathF.Max( _seenFor - dt * 0.5f, 0f );
		if ( _alarm == 0 && (_seenFor > 0.6f || _offTableFor > MissedAfter) ) RaiseAlarm( 1, anySees );
		else if ( _alarm == 1 && _seenFor > 4f ) RaiseAlarm( 2, true );

		if ( _alarm < 3 && now >= _nextIntercom )
		{
			_nextIntercom = now + 38f;
			Say( "INTERCOM", Pick( new[]
			{
				"Theatre two, prep for the procedure. Bone saw, rib spreader, the big jars. And a mop.",
				"Reminder: specimens do not have names. Stop writing {name} on the charts.",
				"Would the owner of the {object} left in the break room please collect it.",
				"Dr. Hale to theatre two. Dr. Hale. It is nearly time.",
				"Whoever is keeping yoghurt in the specimen fridge: that was not yoghurt.",
				"Staff are reminded that the probe is not a toy. It is a shared resource.",
				"The vending machine on sub-level two is not a containment unit. Stop putting things in it.",
			} ) );
		}
	}

	void RaiseAlarm( int level, bool seen )
	{
		if ( level <= _alarm ) return;
		_alarm = level;
		_seenFor = 0f;
		Sump.Sfx( "lab_alarm_" + level, Arena.Player.WorldPosition );
		FlashbackArena.SetSign( _alarmSign, level >= 3 ? "POWER FAILURE" : level == 2 ? "LOCKDOWN" : "CODE GREY", Color.Red );

		switch ( level )
		{
			case 1:
				Say( "ORDERLY", seen ? "It's off the table! Code grey, code grey!" : "Theatre two is empty. The straps are broken. Code grey." );
				break;
			case 2:
				Say( "INTERCOM", "Lockdown. All orderlies to the corridors. It does not leave this building." );
				// The reserve comes out and walks the corridors.
				for ( int i = 0; i < _reserve.Count; i++ )
				{
					var r = _reserve[i];
					r.Route = i % 2 == 0
						? new[] { Arena.P( 650f, 150f ), Arena.P( 650f, 0f ), Arena.P( 1080f, 0f ), Arena.P( 650f, 0f ) }
						: new[] { Arena.P( 900f, -150f ), Arena.P( 900f, 0f ), Arena.P( 520f, 0f ), Arena.P( 900f, 0f ) };
				}
				break;
			case 3:
				Say( "INTERCOM", "...", 2f );
				Say( "DR. HALE", "The doors! Every door is open! Dock, everyone to the dock, NOW!" );
				break;
		}
	}

	void Doors( Vector3 local )
	{
		// The plant room door reads the keycard.
		if ( !_cardDoorOpen && (local - new Vector3( 430f, -700f, 0f )).WithZ( 0f ).Length < 90f )
		{
			if ( _hasCard )
			{
				_cardDoorOpen = true;
				if ( _cardDoor.IsValid() ) _cardDoor.Enabled = false;
				Arena.Nav?.MarkDirty( _cardDoor );
				Sump.Sfx( "lab_keycard_ok", Arena.P( 450f, -700f, 50f ) );
			}
			else Sump.Prompt = "Locked. It wants a keycard";
		}

		if ( !_powerCut && (local - new Vector3( 1120f, 0f, 0f )).WithZ( 0f ).Length < 110f )
			Sump.Prompt = "A security door. It will not open while it has power";
	}

	void Things( Vector3 local, float now )
	{
		var a = Arena;

		if ( !_hasCard && (local - _keycardAt).WithZ( 0f ).Length < TakeRadius )
		{
			_hasCard = true;
			if ( _keycard.IsValid() ) _keycard.Destroy();
			Sump.Sfx( "lab_keycard_take", a.Player.WorldPosition );
			Rules.Reach( "keycard", a.Player.WorldPosition, a.Player.Look.yaw, 2 );
			Say( Who, "A keycard. The yellow door, at the south end of the long corridor." );
		}

		if ( !_powerCut && (local - Breaker).WithZ( 0f ).Length < 75f )
		{
			_powerCut = true;
			CutPower();
			Rules.Reach( "power", a.Player.WorldPosition, a.Player.Look.yaw, 3 );
		}

		if ( !_keepsakeTaken && (local - _keepsakeAt).WithZ( 0f ).Length < TakeRadius )
		{
			_keepsakeTaken = true;
			if ( _keepsake.IsValid() ) _keepsake.Destroy();
			Sump.Sfx( "flashback_keepsake", a.Player.WorldPosition );
			Say( Who, "{thing}. Somebody left it on the table next to a cold coffee. It was the only thing in that building that was not for cutting.", 7f );
		}

		// The technician with the sandwich. He has seen nothing. He is on his break.
		if ( !_techSpoke && (local - _fatGuyAt).WithZ( 0f ).Length < 170f )
		{
			_techSpoke = true;
			Sump.Sfx( "fatguy_munch", a.P( _fatGuyAt ) );
			Say( "TECHNICIAN", "(chewing) ...I'm on my break. I didn't see you. You didn't see the sandwich.", 6f );
		}
	}

	/// <summary>The lights go red and every door fails open.</summary>
	void CutPower()
	{
		var a = Arena;
		Sump.Sfx( "lab_power_down", a.Player.WorldPosition );
		a.Player.Kick( Vector3.Down * 14f );

		foreach ( var lamp in _lamps )
			if ( lamp.IsValid() ) lamp.LightColor = new Color( 0.9f, 0.06f, 0.04f );
		if ( a.Ambient.IsValid() ) a.Ambient.Color = new Color( 0.1f, 0.02f, 0.02f );

		foreach ( var door in new[] { _theatreDoor, _cardDoor, _securityDoor } )
			if ( door.IsValid() ) { door.Enabled = false; a.Nav?.MarkDirty( door ); }
		_cardDoorOpen = true;
		_breaker.Enabled = false;
		FlashbackArena.Tint( _doorLight, new Color( 0.2f, 0f, 0f ) );

		RaiseAlarm( 3, false );
		Say( Who, "Dark. Every lock in the building just let go. The way out is east, where the trucks come in." );
	}

	/// <summary>Caught: wheeled back to the theatre and strapped down again, with less time left.</summary>
	void WheelBack()
	{
		var a = Arena;
		a.Crowd.ReleaseAll();
		a.Crowd.Grace( 6f );
		foreach ( var watcher in _staff ) watcher.Reset();
		foreach ( var watcher in _reserve ) watcher.Reset();

		Rules.Elapsed = MathF.Min( Rules.Elapsed + WheelBackPenalty, MathF.Max( Rules.TimeLimit - 20f, 0f ) );
		Sump.Fade = 1f;
		_blackUntil = RealTime.Now + 1.3f;
		_seenFor = 0f;
		_leftTheatre = false;
		Sump.Sfx( "lab_gurney", a.Player.WorldPosition );

		a.Player.Unpin();
		Sump.Teleport( a.P( Table ), a.Yaw( 0f ) );
		Strap( StrapsAfterCapture );
		Say( "ORDERLY", Pick( new[] { "Back on the table. Double the buckles this time.", "Got it. Hold its... are those legs? Hold those.", "Wheel it back. Hale wants it intact. Mostly. He said mostly." } ) );
	}

	void UpdateObjective()
	{
		if ( _straps > 0 ) { Rules.Objective = "Break the straps before the procedure begins"; return; }
		Rules.Meter = -1f;
		string alarm = _alarm switch { 0 => "", 1 => "  [CODE GREY]", 2 => "  [LOCKDOWN]", _ => "  [POWER OUT]" };
		Rules.Objective = (_powerCut ? "Get out through the loading dock, east along the corridor"
			: _hasCard ? "Cut the power: the plant room, yellow door, south end of the long corridor"
			: !_leftTheatre ? "Get out of the theatre: the door when its light is green, or the vent"
			: "Find a keycard: the office, north end of the long corridor") + alarm;
	}

	public override void Won()
	{
		Sump.Sfx( "lab_outside", Arena.Player.WorldPosition );
		Say( "INTERCOM", "It is outside. Repeat, it is OUTSIDE. ...Log it as a clerical error.", 6f );
	}

	public override void Rewind( FlashbackCheckpoint to )
	{
		_blackUntil = 0f;
		_seenFor = 0f;
		foreach ( var watcher in _staff ) watcher.Reset();
		foreach ( var watcher in _reserve ) watcher.Reset();

		// The alarm is remembered only as far as the checkpoint had got: calm on the table, grey after.
		if ( !_powerCut ) _alarm = Math.Min( _alarm, to.Stage >= 1 ? 1 : 0 );
		if ( to.Stage == 0 ) { _leftTheatre = false; Strap( StrapsAtStart ); }
		else { _straps = 0; Arena.Crowd.Struggling = false; }
	}
}