The FlashbackRunner component. Listens for Sump.FlashbackRequested, fades out the hub, has the genre's Flashback build an arena at FlashbackOrigin, puts the player into the misfit's body, and runs the rules through card, play, rewind, freeze and white-out stages before tearing everything down and calling Sump.EndFlashback. Also exposes the current rules, crowd and body to the HUD.
using System;
/// <summary>
/// Runs a misfit's first contact with humans as a playable flashback. Healing the misfits is the
/// game, and this is how it is done: the player walks into the memory in the misfit's own body,
/// plays it through in that memory's own genre, and winning heals the misfit.
///
/// One framework for every genre. It listens for <see cref="Sump.FlashbackRequested"/>, then:
/// fades out, hides the hub, has the genre's <see cref="Flashback"/> build its arena far away at
/// <see cref="Sump.FlashbackOrigin"/>, puts the player there in the misfit's body
/// (<see cref="BodyOverride"/>), shows the title card, and runs the genre's
/// <see cref="FlashbackRules"/>. Going wrong is not the end: the memory rewinds to its last
/// checkpoint a few times, and the player can always let go of it with a key. Either way it
/// finishes by tearing the arena down, putting the player back exactly as they were, showing the
/// hub and calling <see cref="Sump.EndFlashback"/>.
/// The bootstrap adds this to the Sump object.
/// </summary>
[Title( "Flashback Runner" ), Category( "Sump" ), Icon( "history" )]
public sealed class FlashbackRunner : Component
{
public static FlashbackRunner Current { get; private set; }
/// <summary>Name of this module's speed factor on the controller.</summary>
public const string SpeedName = "flashback";
// ---- Tuning ---------------------------------------------------------------------------------
/// <summary>Seconds the fades to and from black take.</summary>
[Property, Group( "Timing" )] public float FadeSeconds { get; set; } = 0.9f;
/// <summary>Seconds the title card (name, place and year, a line of backstory) stays up.</summary>
[Property, Group( "Timing" )] public float CardSeconds { get; set; } = 5.5f;
/// <summary>Seconds the won memory stands frozen while the misfit speaks, before the white-out.</summary>
[Property, Group( "Timing" )] public float FreezeSeconds { get; set; } = 4.5f;
[Property, Group( "Timing" )] public float WhiteOutSeconds { get; set; } = 1.8f;
/// <summary>How slowly the world runs while the won memory is frozen (1 = normal speed).</summary>
[Property, Group( "Timing" ), Range( 0.02f, 1f )] public float FreezeTimeScale { get; set; } = 0.05f;
/// <summary>How many times a memory rewinds to its last checkpoint before it closes, unhealed.</summary>
[Property, Group( "Rules" )] public int MaxRewinds { get; set; } = 3;
/// <summary>Hold this to let go of the memory and return to the Sump, unhealed. "Reload" is R.</summary>
[Property, Group( "Rules" )] public string LeaveAction { get; set; } = "Reload";
[Property, Group( "Rules" )] public float LeaveHoldSeconds { get; set; } = 1.5f;
/// <summary>Put the player back where they stood when the memory began, instead of at the hub's spawn.</summary>
[Property, Group( "Rules" )] public bool ReturnToWhereTheyStood { get; set; } = true;
/// <summary>For testing: wins the current flashback at once. Clears itself.</summary>
[Property, Group( "Testing" )] public bool DebugSkip { get; set; }
/// <summary>For testing: a key that wins the current flashback at once. "Slot0" is the 0 key. Empty for none.</summary>
[Property, Group( "Testing" )] public string DebugWinAction { get; set; } = ""; // off in the shipped game; set to an input action to win a memory while testing
// ---- Published for other modules (the HUD, the hub, the grafts) --------------------------------
/// <summary>True from the moment a memory is asked for until the player is back in the Sump.</summary>
public bool Running => _stage != Stage.Idle;
/// <summary>True only while the player has the controls inside the memory.</summary>
public bool Playing => _stage == Stage.Play;
/// <summary>The misfit whose memory this is, or null.</summary>
public MisfitProfile Profile { get; private set; }
/// <summary>The kind of game being played ("FARM HORROR"), or empty.</summary>
public string GenreTitle => _flashback?.GenreTitle ?? "";
/// <summary>Where and when the memory is set, or empty.</summary>
public string Place => _flashback?.Place ?? "";
/// <summary>The rules being played, or null: objective, clock, meter, checkpoints.</summary>
public FlashbackRules Rules => _flashback?.Rules;
/// <summary>The humans' host in the current memory, or null: Held, Pinned, Struggle, ShakeForce.</summary>
public FlashbackCrowd Crowd => _arena?.Crowd;
/// <summary>The body the player is wearing, or null.</summary>
public MisfitBody StandIn => _standIn;
/// <summary>Rewinds still to go before the memory closes.</summary>
public int RewindsLeft { get; private set; }
/// <summary>0 to 1: how far the won memory has burnt out to white. For the HUD to draw.</summary>
public float WhiteOut { get; private set; }
/// <summary>0 to 1: how long the leave key has been held.</summary>
public float LeaveProgress { get; private set; }
/// <summary>Wins the current flashback now.</summary>
public void Win()
{
if ( _stage == Stage.Play ) StartFreeze();
}
/// <summary>Leaves the current flashback now, unhealed.</summary>
public void Leave()
{
if ( _stage == Stage.Play || _stage == Stage.Card ) Close( "THE MEMORY CLOSES", "You let go of it. It will still be there." );
}
// ---- State ----------------------------------------------------------------------------------
enum Stage { Idle, FadeOut, Card, Play, RewindOut, RewindIn, Freeze, White, CloseOut, Return }
Stage _stage = Stage.Idle;
float _t; // real seconds in this stage
Flashback _flashback;
FlashbackArena _arena;
MisfitBody _standIn;
BodyOverride.Snapshot _snapshot;
BodyHandling _handling;
ReptileController _player;
Vector3 _stood;
float _stoodYaw;
string _hubObjective = "";
string _lostReason = "";
bool _healed;
bool _faulted;
Color _ambientAtWin;
protected override void OnStart()
{
if ( Scene.IsEditor ) return;
Current = this;
Sump.FlashbackRequested += OnRequested;
}
protected override void OnDestroy()
{
Sump.FlashbackRequested -= OnRequested;
if ( Running )
{
// Removed in the middle of a memory: the body, the clock and the controls are put
// back (TearDown), and unless the whole scene is going, so is the hub.
bool inside = _stage != Stage.Return;
TearDown();
if ( _player.IsValid() ) { _player.InputLocked = false; _player.ForcedWish = null; }
WhiteOut = 0f;
_stage = Stage.Idle;
if ( inside && GameObject.IsValid() && Sump.Mode == SumpMode.Flashback )
{
SumpCavern.SetHubVisible( true );
Sump.Fade = 0f;
Sump.CardTitle = Sump.CardLine = "";
Sump.EndFlashback( false );
}
}
if ( Current == this ) Current = null;
}
void OnRequested( MisfitProfile profile )
{
if ( profile is null ) return;
// Asked again while the last memory is still fading back in: that fade is simply cut short.
if ( _stage == Stage.Return ) { WhiteOut = 0f; Profile = null; Go( Stage.Idle ); }
if ( Running ) return;
_player = Sump.Player;
if ( !_player.IsValid() ) { Sump.EndFlashback( false ); return; }
Profile = profile;
_healed = false;
_faulted = false;
RewindsLeft = Math.Max( MaxRewinds, 0 );
WhiteOut = 0f;
LeaveProgress = 0f;
_hubObjective = Sump.Objective;
_stood = _player.WorldPosition;
_stoodYaw = _player.Look.yaw;
_snapshot = BodyOverride.Take( _player );
_player.InputLocked = true;
_player.ForcedWish = null;
Sump.Sfx( "flashback_enter", _player.WorldPosition );
Go( Stage.FadeOut );
}
void Go( Stage stage )
{
_stage = stage;
_t = 0f;
}
protected override void OnUpdate()
{
if ( Scene.IsEditor || _stage == Stage.Idle ) return;
_t += RealTime.Delta;
switch ( _stage )
{
case Stage.FadeOut:
Hold();
Sump.Fade = MathF.Max( Sump.Fade, Math.Clamp( _t / MathF.Max( FadeSeconds, 0.05f ), 0f, 1f ) );
if ( _t >= FadeSeconds ) Enter();
break;
case Stage.Card:
// Black for a moment while the place settles, then it comes up behind the card.
Hold();
Sump.Fade = 1f - Math.Clamp( (_t - 1.6f) / 1.6f, 0f, 1f );
if ( _t >= CardSeconds ) BeginPlay();
break;
case Stage.Play: Play(); break;
case Stage.RewindOut:
Hold();
Sump.Fade = Math.Clamp( _t / 0.5f, 0f, 1f );
if ( _t >= 0.5f ) DoRewind();
break;
case Stage.RewindIn:
Sump.Fade = 1f - Math.Clamp( (_t - 1.2f) / 0.7f, 0f, 1f );
if ( _t < 1.9f ) break;
Sump.CardTitle = Sump.CardLine = "";
Go( Stage.Play );
break;
case Stage.Freeze:
Hold();
Animate();
if ( _t >= FreezeSeconds ) { Sump.Sfx( "flashback_whiteout", _player.WorldPosition ); Go( Stage.White ); }
break;
case Stage.White:
Hold();
WhiteOut = Math.Clamp( _t / MathF.Max( WhiteOutSeconds, 0.05f ), 0f, 1f );
// Until the HUD draws the white itself: the memory's own light burns everything out.
if ( _arena?.Ambient is { } ambient && ambient.IsValid() )
ambient.Color = Color.Lerp( _ambientAtWin, new Color( 40f, 40f, 40f ), WhiteOut * WhiteOut );
if ( _t >= WhiteOutSeconds ) Finish();
break;
case Stage.CloseOut:
Hold();
Sump.Fade = MathF.Max( Sump.Fade, Math.Clamp( _t / MathF.Max( FadeSeconds, 0.05f ), 0f, 1f ) );
if ( _t >= FadeSeconds + 1.6f ) Finish();
break;
case Stage.Return:
Sump.Fade = 1f - Math.Clamp( (_t - 0.4f) / 1.2f, 0f, 1f );
WhiteOut = MathF.Max( WhiteOut - RealTime.Delta * 1.5f, 0f );
if ( _t < 1.6f ) break;
Sump.Fade = 0f;
WhiteOut = 0f;
Profile = null;
Go( Stage.Idle );
break;
}
}
/// <summary>The player has no controls while the runner is between things.</summary>
void Hold()
{
if ( !_player.IsValid() ) return;
_player.InputLocked = true;
_player.ForcedWish = null;
}
// ---- Going in -------------------------------------------------------------------------------
/// <summary>The screen is black: swap the Sump for the memory.</summary>
void Enter()
{
try
{
_flashback = Flashback.Create( Profile.Genre );
if ( _flashback is null ) throw new InvalidOperationException( $"no flashback for genre {Profile.Genre}" );
SumpCavern.SetHubVisible( false );
_handling = BodyOverride.For( Profile.Plan );
_arena = new FlashbackArena( Profile, _player, _handling, (int)Profile.Genre + 1 );
_flashback.Setup( _arena );
_flashback.Build();
_arena.Crowd.Adopt( _player );
_arena.Crowd.Live = false;
// Slow bodies get longer on any clock.
_flashback.Rules.TimeLimit *= _handling.Patience;
_standIn = BodyOverride.Apply( _player, Profile, _handling, _snapshot );
float floor = _arena.FloorZ;
_player.FloorHeight = _ => floor;
_player.Unpin();
MoveTo( _flashback.Start, _flashback.StartYaw );
Sump.CardTitle = Profile.Name;
Sump.CardLine = string.IsNullOrEmpty( Profile.Backstory ) ? _flashback.Place : $"{_flashback.Place}\n{Profile.Backstory}";
Sump.Objective = "";
Go( Stage.Card );
}
catch ( Exception e )
{
Log.Warning( $"Flashback could not be built: {e}" );
_faulted = true;
_healed = false;
Finish();
}
}
void BeginPlay()
{
Sump.CardTitle = Sump.CardLine = "";
Sump.Fade = 0f;
_player.InputLocked = false;
var rules = _flashback.Rules;
rules.Reach( "start", _flashback.Start, _flashback.StartYaw );
_arena.Crowd.Live = true;
Guard( () => _flashback.Begin() );
if ( !string.IsNullOrEmpty( _handling.Hint ) ) Sump.Say( MisfitVoice.ShortName( Profile ), _handling.Hint, 7f );
if ( !string.IsNullOrEmpty( LeaveAction ) ) Sump.Say( "", "R (hold) let go of this memory. It will keep.", 6f );
Go( Stage.Play );
}
// ---- Playing --------------------------------------------------------------------------------
void Play()
{
// A memory that has failed once is not run again (it would fail again, every frame), and
// one whose pieces have gone cannot be played at all: it closes and the player goes home.
if ( _faulted || _flashback is null || _arena is null || !_player.IsValid() )
{
Close( "THE MEMORY CLOSES", "It slipped away. It is not ready to be remembered. Come back to it." );
return;
}
var rules = _flashback.Rules;
var crowd = _arena.Crowd;
float dt = Time.Delta;
// The prompt line belongs to the memory while it runs: cleared, then set again by whoever wants it.
Sump.Prompt = null;
rules.Elapsed += dt;
Guard( () => rules.Update?.Invoke( dt ) );
if ( _stage != Stage.Play ) return; // the flashback itself won or left
Animate();
Sump.Objective = Describe( rules );
if ( crowd.Held )
Sump.Prompt = crowd.Pinned
? "PINNED. SPACE buck them off (or thrash the mouse)"
: "Hands on you. SPACE buck them off (or thrash the mouse)";
// Testing: straight to the end.
if ( DebugSkip || (!string.IsNullOrEmpty( DebugWinAction ) && Input.Pressed( DebugWinAction )) )
{
DebugSkip = false;
StartFreeze();
return;
}
// The way out that is always there.
if ( !string.IsNullOrEmpty( LeaveAction ) && Input.Down( LeaveAction ) )
{
LeaveProgress = MathF.Min( LeaveProgress + RealTime.Delta / MathF.Max( LeaveHoldSeconds, 0.1f ), 1f );
Sump.Prompt = "Letting go of the memory...";
if ( LeaveProgress >= 1f ) { Leave(); return; }
}
else LeaveProgress = 0f;
bool won = false;
Guard( () => won = rules.Won is not null && rules.Won() );
if ( won ) { StartFreeze(); return; }
string lost = null;
Guard( () => lost = rules.Lost?.Invoke() );
if ( lost is null && rules.PinLoseSeconds > 0f && crowd.PinnedSeconds >= rules.PinLoseSeconds ) lost = rules.PinLoseLine;
if ( lost is null && rules.TimeLimit > 0f && rules.Elapsed >= rules.TimeLimit ) lost = rules.TimeUpLine;
if ( lost is not null ) { Lose( lost ); return; }
// Fell out of the memory somehow: quietly back to the last checkpoint.
var from = _player.WorldPosition - _arena.Origin;
if ( from.Length > rules.BoundsRadius || from.z < -300f )
{
var back = rules.Checkpoint;
if ( back is not null ) MoveTo( back.Feet, back.Yaw );
}
}
/// <summary>The stand-in body moves and frets with the player.</summary>
void Animate()
{
if ( !_standIn.IsValid() || !_player.IsValid() ) return;
_standIn.MoveSpeed = _player.Velocity.Length;
float fear = _arena.Crowd.Pinned ? 1f : _arena.Crowd.Held ? 0.7f : 0.15f;
_standIn.Agitation = _standIn.Agitation + (fear - _standIn.Agitation) * Math.Clamp( Time.Delta * 3f, 0f, 1f );
}
/// <summary>The objective line: the goal, then the clock and the meter if the rules have them.</summary>
static string Describe( FlashbackRules rules )
{
string text = rules.Objective ?? "";
if ( rules.TimeLimit > 0f )
{
int seconds = (int)MathF.Ceiling( rules.TimeLeft );
text += $" | {rules.TimeLabel} {seconds / 60}:{seconds % 60:00}";
}
if ( rules.Meter >= 0f )
{
int filled = (int)MathF.Round( Math.Clamp( rules.Meter, 0f, 1f ) * 10f );
text += $" | {rules.MeterLabel} [{new string( '#', filled )}{new string( '-', 10 - filled )}]";
}
return text;
}
/// <summary>Runs a piece of a flashback, so a mistake in one memory cannot take the Sump down with it.</summary>
void Guard( Action action )
{
try { action(); }
catch ( Exception e )
{
if ( !_faulted ) Log.Warning( $"Flashback error ({GenreTitle}): {e}" );
_faulted = true;
}
}
// ---- Going wrong ----------------------------------------------------------------------------
void Lose( string reason )
{
_lostReason = reason ?? "";
Sump.Prompt = null;
Sump.Sfx( "flashback_lose", _player.WorldPosition );
if ( RewindsLeft <= 0 )
{
Close( "THE MEMORY CLOSES", $"{_lostReason} It is not ready to be remembered. Come back to it." );
return;
}
RewindsLeft--;
Go( Stage.RewindOut );
}
void DoRewind()
{
var rules = _flashback.Rules;
var crowd = _arena.Crowd;
var back = rules.Checkpoint;
crowd.ReleaseAll();
crowd.Grace( 4f );
_player.Unpin();
_player.SetSpeedFactor( SpeedName, 1f );
if ( back is not null )
{
// The clock goes back with the memory, and never to less than a fighting chance.
rules.Elapsed = back.Elapsed;
if ( rules.TimeLimit > 0f ) rules.Elapsed = MathF.Min( rules.Elapsed, MathF.Max( rules.TimeLimit - rules.RewindGrace, 0f ) );
MoveTo( back.Feet, back.Yaw );
Guard( () => _flashback.Rewind( back ) );
}
Sump.CardTitle = "THE MEMORY REWINDS";
Sump.CardLine = RewindsLeft > 0 ? $"{_lostReason}\nIt will rewind {RewindsLeft} more time{(RewindsLeft == 1 ? "" : "s")}." : $"{_lostReason}\nThis is the last time it will rewind.";
Sump.Sfx( "flashback_rewind", _player.WorldPosition );
_player.InputLocked = false;
Go( Stage.RewindIn );
}
void Close( string title, string line )
{
_healed = false;
Sump.Prompt = null;
Sump.CardTitle = title;
Sump.CardLine = line;
if ( _arena is not null ) _arena.Crowd.Live = false;
Go( Stage.CloseOut );
}
// ---- Winning --------------------------------------------------------------------------------
/// <summary>The memory freezes where it is, the misfit speaks, and it all burns out to white.</summary>
void StartFreeze()
{
_healed = true;
Scene.TimeScale = FreezeTimeScale;
_arena.Crowd.ReleaseAll();
_arena.Crowd.Live = false;
_ambientAtWin = _arena.Ambient.IsValid() ? _arena.Ambient.Color : Color.Gray;
Sump.Prompt = null;
Sump.Objective = "";
Guard( () => _flashback.Won() );
Sump.Say( MisfitVoice.ShortName( Profile ), MisfitVoice.Thanks( Profile ), FreezeSeconds + WhiteOutSeconds + 3f );
Sump.Sfx( "flashback_freeze", _player.WorldPosition );
Go( Stage.Freeze );
}
// ---- Coming back ----------------------------------------------------------------------------
/// <summary>Out of the memory (won, lost or broken): everything is put back and the Sump is told.</summary>
void Finish()
{
Sump.Fade = 1f;
TearDown();
SumpCavern.SetHubVisible( true );
var home = ReturnToWhereTheyStood && _stood != Vector3.Zero ? _stood + Vector3.Up * 6f : Sump.HubSpawn;
if ( _player.IsValid() ) MoveTo( home, _stoodYaw );
Sump.CardTitle = Sump.CardLine = "";
Sump.Prompt = null;
Sump.Objective = _hubObjective ?? "";
Sump.Sfx( _healed ? "flashback_healed" : "flashback_return", home );
Sump.EndFlashback( _healed );
Go( Stage.Return );
}
/// <summary>Destroys the arena and puts back everything that was changed on the player.</summary>
void TearDown()
{
if ( Scene is not null ) Scene.TimeScale = 1f;
// The body first: it sits on the player, not in the arena.
BodyOverride.Remove( _player, _standIn, _snapshot );
_standIn = null;
if ( _arena is not null && _arena.Root.IsValid() ) _arena.Root.Destroy();
if ( ReferenceEquals( CrowdHosts.Fallback, _arena?.Crowd ) ) CrowdHosts.Fallback = null;
_arena = null;
_flashback = null;
}
void MoveTo( Vector3 feet, float yaw )
{
if ( SumpBootstrap.Current.IsValid() ) Sump.Teleport( feet, yaw );
else _player.Teleport( feet, yaw );
}
}