...
using System;
using System.Collections.Generic;
using System.Linq;
// THE SUMP: shared types and state. Every Sump module talks through what is in this folder, so
// the modules (Cavern, Generator, Misfits, Trauma, Flashbacks, Grafts, Hub, Finale, Presentation)
// do not need to know about each other. Design: playtest/patch-sump.md.
public enum BodyPlan { GasSac, CrystalLattice, Swarm, Jelly, Insectoid, Fungus, Machine }
/// <summary>How a misfit's first meeting with humans went. It decides the flashback and the twisted ability.</summary>
public enum FirstContact { ShotOnFarm, Dissected, WorshippedThenSold, BecameMeme, AdoptedThenForgotten }
public enum TwistedAbility
{
/// <summary>The dissected one: opens its own body as a door to somewhere else.</summary>
BodyDoor,
/// <summary>The meme: only exists while somebody is looking at it.</summary>
OnlyWhileWatched,
/// <summary>Shot on a farm: anything thrown or fired bends toward it.</summary>
BulletMagnet,
/// <summary>Worshipped then sold: it can put a price on anything, and the thing obeys the price.</summary>
PriceTag,
/// <summary>Adopted then forgotten: it shrinks to a toy and cannot be noticed until it is picked up.</summary>
ToyStillness,
}
public enum Phobia { Crowds, Weight, Light }
public enum FlashbackGenre { FarmHorror, LabEscape, TalkShow }
public enum SumpMode { Arrival, Hub, Flashback, Finale, Ended }
/// <summary>One misfit: everything rolled about it. Plain data; filled in by MisfitGenerator.</summary>
public sealed class MisfitProfile
{
public int Seed { get; set; }
public int Index { get; set; }
public string Name { get; set; } = "Nobody";
public BodyPlan Plan { get; set; }
public FirstContact Contact { get; set; }
public TwistedAbility Ability { get; set; }
public FlashbackGenre Genre { get; set; }
// ---- Scars ----
/// <summary>What it cannot bear, as a short phrase ("open sky", "the sound of engines").</summary>
public string Fear { get; set; } = "";
/// <summary>Machine-readable kind of that fear, so behaviour can react: "light", "noise", "touch", "crowds", "open", "eyes".</summary>
public string FearKind { get; set; } = "light";
/// <summary>A physical tic ("flinches left every few seconds").</summary>
public string Twitch { get; set; } = "";
/// <summary>How its speech is broken: "stutter", "echo", "jingle", "backwards", "whisper", "prices", "none".</summary>
public string SpeechTic { get; set; } = "none";
/// <summary>The human object it clings to ("Walkman", "crucifix", "McDonald's toy").</summary>
public string ClungObject { get; set; } = "";
// ---- Story ----
/// <summary>One line: who it was and what happened.</summary>
public string Backstory { get; set; } = "";
/// <summary>Where it came from and what it was sent to do ("scout", "tourist", "invader", "abductor").</summary>
public string Role { get; set; } = "scout";
// ---- Looks ----
public Color Primary { get; set; } = Color.White;
public Color Secondary { get; set; } = Color.Gray;
public float Size { get; set; } = 1f;
// ---- Progress ----
public bool Healed { get; set; }
}
/// <summary>
/// What persists for the whole Sump: who lives there, who is healed, what the player is afraid
/// of. Static, so it survives scene changes; saved to disk so it survives quitting.
/// </summary>
public static class SumpState
{
public const int MisfitCount = 9;
/// <summary>Healed misfits needed before the way down to the heart opens.</summary>
public const int FinaleNeeds = 3;
const string SaveFile = "sump.json";
public static int Seed { get; private set; }
public static bool Started { get; private set; }
public static List<MisfitProfile> Misfits { get; private set; } = new();
public static Phobia PlayerPhobia { get; set; }
public static bool FinaleDone { get; set; }
public static int HealedCount => Misfits.Count( m => m.Healed );
public static IEnumerable<MisfitProfile> Healed => Misfits.Where( m => m.Healed );
public static bool FinaleUnlocked => HealedCount >= FinaleNeeds;
/// <summary>Somebody was healed just now.</summary>
public static event Action<MisfitProfile> MisfitHealed;
/// <summary>Anything in here changed.</summary>
public static event Action Changed;
class SaveData
{
public int Seed { get; set; }
public int Phobia { get; set; }
public List<int> Healed { get; set; } = new();
public bool FinaleDone { get; set; }
public Dictionary<string, string> Notes { get; set; } = new();
}
// Anything else a module wants remembered between visits (where a shrine was put, which
// radio frequencies are open), as plain text under a key of its own choosing.
static Dictionary<string, string> _notes = new();
public static string GetNote( string key, string fallback = "" ) => _notes.TryGetValue( key, out var value ) ? value : fallback;
public static void SetNote( string key, string value )
{
if ( _notes.TryGetValue( key, out var old ) && old == value ) return;
_notes[key] = value;
Save();
}
/// <summary>Loads the save, or starts a new Sump. Safe to call any number of times.</summary>
public static void EnsureStarted()
{
if ( Started ) return;
SaveData save = null;
try { if ( FileSystem.Data.FileExists( SaveFile ) ) save = FileSystem.Data.ReadJson<SaveData>( SaveFile ); }
catch ( Exception e ) { Log.Warning( $"Sump save unreadable, starting again: {e.Message}" ); }
_notes = save?.Notes ?? new Dictionary<string, string>();
if ( save is not null && save.Seed != 0 ) Begin( save.Seed, (Phobia)save.Phobia, save.Healed, save.FinaleDone );
else Begin( Game.Random.Next( 1, int.MaxValue ), RollPhobia(), null, false );
}
/// <summary>Throws everything away and rolls a new Sump (and a new fear for the player).</summary>
public static void Reset()
{
_notes = new Dictionary<string, string>();
Begin( Game.Random.Next( 1, int.MaxValue ), RollPhobia(), null, false );
Save();
}
static Phobia RollPhobia() => (Phobia)Game.Random.Next( 0, 3 );
static void Begin( int seed, Phobia phobia, List<int> healed, bool finaleDone )
{
Seed = seed;
PlayerPhobia = phobia;
FinaleDone = finaleDone;
Misfits = new List<MisfitProfile>();
for ( int i = 0; i < MisfitCount; i++ )
{
var profile = MisfitGenerator.Roll( seed, i );
profile.Index = i;
profile.Healed = healed is not null && healed.Contains( i );
Misfits.Add( profile );
}
Started = true;
Changed?.Invoke();
}
/// <summary>Marks a misfit healed. It joins the player, and the hub grows.</summary>
public static void Heal( MisfitProfile profile )
{
if ( profile is null || profile.Healed ) return;
profile.Healed = true;
Save();
MisfitHealed?.Invoke( profile );
Changed?.Invoke();
}
public static void Save()
{
try
{
FileSystem.Data.WriteJson( SaveFile, new SaveData
{
Seed = Seed,
Phobia = (int)PlayerPhobia,
Healed = Misfits.Where( m => m.Healed ).Select( m => m.Index ).ToList(),
FinaleDone = FinaleDone,
Notes = _notes,
} );
}
catch ( Exception e ) { Log.Warning( $"Sump save failed: {e.Message}" ); }
}
}
/// <summary>
/// The live scene's shared noticeboard: who the player is, what mode the Sump is in, and the
/// few things every module needs to show or ask for (a prompt, a spoken line, a fade, a request
/// to start a flashback). The HUD draws from here; nobody calls the HUD directly.
/// </summary>
public static class Sump
{
public static ReptileController Player { get; set; }
public static SumpMode Mode { get; set; } = SumpMode.Arrival;
/// <summary>Where the player stands in the hub (feet), set by the cavern.</summary>
public static Vector3 HubSpawn { get; set; }
/// <summary>Flashbacks are built far from the hub, around here.</summary>
public static readonly Vector3 FlashbackOrigin = new( 60000f, 0f, 0f );
/// <summary>The finale is built far below the hub, around here.</summary>
public static readonly Vector3 FinaleOrigin = new( 0f, 60000f, -20000f );
// ---- For the HUD ----
/// <summary>One-line "press E to..." under the crosshair. Set it every frame you want it shown.</summary>
public static string Prompt { get; set; }
/// <summary>The current goal, top-left.</summary>
public static string Objective { get; set; } = "";
/// <summary>Black over everything, 0 to 1.</summary>
public static float Fade { get; set; }
/// <summary>Big centred title with a smaller line under it; empty for none.</summary>
public static string CardTitle { get; set; } = "";
public static string CardLine { get; set; } = "";
/// <summary>The player's composure, 1 calm to 0 panic. Written by the trauma module.</summary>
public static float Calm { get; set; } = 1f;
/// <summary>Short name of what is frightening the player right now, or empty.</summary>
public static string Dread { get; set; } = "";
public sealed class Line
{
public string Speaker;
public string Text;
public float Until;
}
static readonly List<Line> _lines = new();
/// <summary>Spoken lines still on screen, oldest first.</summary>
public static IReadOnlyList<Line> Lines
{
get
{
_lines.RemoveAll( l => RealTime.Now > l.Until );
return _lines;
}
}
/// <summary>Somebody says something: shown as a subtitle with their name.</summary>
public static void Say( string speaker, string text, float seconds = 4.5f )
{
if ( string.IsNullOrEmpty( text ) ) return;
_lines.Add( new Line { Speaker = speaker ?? "", Text = text, Until = RealTime.Now + seconds } );
while ( _lines.Count > 4 ) _lines.RemoveAt( 0 );
Said?.Invoke( speaker, text );
}
public static event Action<string, string> Said;
// ---- Requests between modules ----
/// <summary>A misfit's first contact is to be played. The flashback module listens.</summary>
public static event Action<MisfitProfile> FlashbackRequested;
public static void RequestFlashback( MisfitProfile profile )
{
if ( profile is null || Mode != SumpMode.Hub ) return;
ActiveFlashback = profile;
Mode = SumpMode.Flashback;
Loading.ShowArea( "Remembering somebody else's worst day", 1.2f );
FlashbackRequested?.Invoke( profile );
}
public static MisfitProfile ActiveFlashback { get; private set; }
/// <summary>The flashback is over. Healed if it was won. Everyone listening puts the hub back.</summary>
public static event Action<MisfitProfile, bool> FlashbackEnded;
public static void EndFlashback( bool healed )
{
var profile = ActiveFlashback;
ActiveFlashback = null;
Mode = SumpMode.Hub;
if ( healed && profile is not null ) SumpState.Heal( profile );
FlashbackEnded?.Invoke( profile, healed );
}
/// <summary>The descent to the heart is to begin. The finale module listens.</summary>
public static event Action FinaleRequested;
public static void RequestFinale()
{
if ( Mode != SumpMode.Hub || !SumpState.FinaleUnlocked ) return;
Mode = SumpMode.Finale;
Loading.ShowArea( "Going down. A long way down", 1.2f );
FinaleRequested?.Invoke();
}
/// <summary>Called when the scene starts: clears everything left from the last time it ran.</summary>
public static void ResetScene()
{
Player = null;
Mode = SumpMode.Arrival;
Prompt = null;
Objective = "";
Fade = 0f;
CardTitle = CardLine = "";
Calm = 1f;
Dread = "";
ActiveFlashback = null;
_hiddenBody.Clear();
_lines.Clear();
FlashbackRequested = null;
FlashbackEnded = null;
FinaleRequested = null;
Said = null;
}
// ---- Helpers everybody needs ----
/// <summary>Puts the player somewhere else at once (feet position), facing a yaw in degrees.</summary>
public static void Teleport( Vector3 feet, float yaw = 0f ) => SumpBootstrap.Current?.Teleport( feet, yaw );
static readonly List<ModelRenderer> _hiddenBody = new();
/// <summary>
/// Hides or shows the lizard's own body (whichever model it is using), for when the player is
/// living through somebody else's memory in somebody else's shape.
/// </summary>
public static void SetPlayerBodyVisible( bool visible )
{
if ( !Player.IsValid() ) return;
if ( visible )
{
foreach ( var renderer in _hiddenBody )
if ( renderer.IsValid() ) renderer.Enabled = true;
_hiddenBody.Clear();
return;
}
var body = Player.Body.IsValid() ? Player.Body : Player.GameObject;
foreach ( var renderer in body.Components.GetAll<ModelRenderer>( FindMode.EverythingInSelfAndDescendants ) )
{
if ( !renderer.Enabled || renderer.Tags.Has( "sump_standin" ) || renderer.GameObject.Tags.Has( "sump_standin" ) ) continue;
renderer.Enabled = false;
_hiddenBody.Add( renderer );
}
}
/// <summary>Plays a Sump sound by short name ("heal_chime"); quiet if the sound does not exist yet.</summary>
public static SoundHandle Sfx( string name, Vector3 position, float volume = 1f )
{
var handle = Sound.Play( $"sounds/sump/{name}.sound", position );
if ( handle.IsValid() ) handle.Volume = volume;
return handle;
}
/// <summary>A new unsaved object under the Sump's root, for things built at runtime.</summary>
public static GameObject Spawn( string name, Vector3 position, GameObject parent = null )
{
var go = new GameObject( parent ?? SumpBootstrap.Current?.GameObject, true, name );
go.Flags |= GameObjectFlags.NotSaved;
go.WorldPosition = position;
return go;
}
/// <summary>A tinted box (models/dev/box.vmdl is a 50-unit cube) with an optional collider. Size in inches.</summary>
public static GameObject Box( GameObject parent, string name, Vector3 position, Vector3 size, Color tint, bool solid = true )
{
var go = Spawn( name, position, parent );
go.WorldScale = size / 50f;
var renderer = go.Components.Create<ModelRenderer>();
renderer.Model = Model.Load( "models/dev/box.vmdl" );
renderer.Tint = tint;
if ( solid )
{
var collider = go.Components.Create<BoxCollider>();
collider.Scale = new Vector3( 50f, 50f, 50f );
collider.Static = true;
}
return go;
}
/// <summary>A tinted sphere (models/dev/sphere.vmdl has radius 32). Radii in inches.</summary>
public static GameObject Ball( GameObject parent, string name, Vector3 position, Vector3 radii, Color tint )
{
var go = Spawn( name, position, parent );
go.WorldScale = radii / 32f;
var renderer = go.Components.Create<ModelRenderer>();
renderer.Model = Model.Load( "models/dev/sphere.vmdl" );
renderer.Tint = tint;
return go;
}
}