Runtime builder for the Sump cavern: makes a sealed CaveGenerator rock from SumpState.Seed, adds ambient/fog, the arrival shaft, landing cushion, junk heaps, glow sacs, fungus, pools and roots, and fills the static layout lists (MisfitSpots, BuildSites, FinaleDoor, Centre, FloorRadius) other modules read. Runs the arrival sequence (shaft hold, fall, landing kick, title card, voices in the dark) or the short wake-up/rope-down variants, and switches the rock off while the player is far away so the controller is not dragged back inside.
using System;
using System.Collections.Generic;
/// <summary>
/// THE SUMP itself: the vast cavern miles under the stadium, the stub of the shaft the lizard
/// drops out of, and the arrival (fall, landing, title card, voices in the dark).
///
/// Everything is built at runtime as unsaved objects. The rock is one <see cref="CaveGenerator"/>
/// (sealed shell, so there is no way out), shaped from <see cref="SumpState.Seed"/>. On top of it
/// this places the mood (ambient, fog, hanging glow sacs, fungus, pools, roots, junk heaps) and
/// works out a layout the other modules read from the static members: <see cref="MisfitSpots"/>,
/// <see cref="BuildSites"/>, <see cref="FinaleDoor"/>, <see cref="FloorHeightAt"/>. They should
/// wait for <see cref="Ready"/>.
///
/// Important for anything built far away (flashbacks, the finale): the lizard keeps itself inside
/// the scene's CaveGenerator, so while the rock exists it cannot leave the cavern. This component
/// takes the rock away when the player is far from the cavern and puts it back when they return
/// (see <see cref="AutoHide"/> and <see cref="SetHubVisible"/>).
/// </summary>
[Title( "Sump Cavern" ), Category( "Sump" ), Icon( "terrain" )]
public sealed class SumpCavern : Component
{
// ---- Published layout (other modules read these) -------------------------------------------
/// <summary>True once the cavern exists and the lists below are filled.</summary>
public static bool Ready { get; private set; }
/// <summary>Hiding places on the cavern floor, spread round the edges, each behind a junk heap. Feet positions.</summary>
public static IReadOnlyList<Vector3> MisfitSpots => _misfitSpots;
/// <summary>Flat clear spots round the landing place, for shrines, the market and the radio room. Nearest first.</summary>
public static IReadOnlyList<Vector3> BuildSites => _buildSites;
/// <summary>A spot on the floor at the cavern's lowest edge, where the way down will open.</summary>
public static Vector3 FinaleDoor { get; private set; }
/// <summary>Middle of the cavern's air (the rock's centre).</summary>
public static Vector3 Centre { get; private set; }
/// <summary>Rough radius of the walkable floor, for anyone who wants to scatter things.</summary>
public static float FloorRadius { get; private set; }
/// <summary>True while the cavern's rock and dressing exist (false while the player is away in a flashback).</summary>
public static bool HubVisible { get; private set; }
// Not carried across a hotload: the engine cannot copy these lists over, and they are rebuilt with the cavern.
[SkipHotload] static readonly List<Vector3> _misfitSpots = new();
[SkipHotload] static readonly List<Vector3> _buildSites = new();
static SumpCavern _instance;
/// <summary>
/// Height of the ground under a point. Uses the real rock while the cavern is there, and the
/// cavern's floor formula otherwise (or outside the floor), so it always answers.
/// </summary>
public static float FloorHeightAt( Vector3 point )
{
var cavern = _instance;
if ( !cavern.IsValid() ) return point.z;
return cavern.FloorAt( point.x, point.y, out _ ).z;
}
/// <summary>
/// Shows or removes the whole hub: the rock (and with it the shell that keeps the lizard in),
/// its lights, fog and dressing. Call with false before taking the player far away and true
/// before bringing them back. With <see cref="AutoHide"/> on this also happens by itself.
/// </summary>
public static void SetHubVisible( bool visible )
{
if ( _instance.IsValid() ) _instance.ApplyVisible( visible );
}
// ---- Shape ----------------------------------------------------------------------------------
/// <summary>Half-extents of the cavern before noise, in inches. The default is over 7,000 inches across.</summary>
[Property, Group( "Shape" )] public Vector3 Size { get; set; } = new( 3800f, 3200f, 1900f );
/// <summary>Where the cavern's centre is, relative to this object.</summary>
[Property, Group( "Shape" )] public Vector3 CentreOffset { get; set; } = Vector3.Zero;
/// <summary>Shell subdivision. 6 is about 80k triangles: needed at this size, and the costliest setting.</summary>
[Property, Group( "Shape" ), Range( 4, 6 )] public int Detail { get; set; } = 6;
[Property, Group( "Shape" ), Range( 0f, 0.6f )] public float WallNoise { get; set; } = 0.34f;
[Property, Group( "Shape" ), Range( 0f, 0.2f )] public float WallDetail { get; set; } = 0.07f;
[Property, Group( "Shape" )] public float NoiseFrequency { get; set; } = 1.9f;
/// <summary>Where the floor cuts the shell, from -1 (very bottom) to 0 (halfway up).</summary>
[Property, Group( "Shape" ), Range( -0.9f, 0f )] public float FloorLevel { get; set; } = -0.45f;
/// <summary>Height of the floor's rolling rises and dips, in inches.</summary>
[Property, Group( "Shape" )] public float FloorBumpHeight { get; set; } = 150f;
[Property, Group( "Shape" )] public string RockMaterial { get; set; } = "materials/cave/cave_rock.vmat";
[Property, Group( "Shape" )] public float TextureScale { get; set; } = 700f;
[Property, Group( "Shape" )] public int Stalactites { get; set; } = 150;
[Property, Group( "Shape" )] public int Stalagmites { get; set; } = 80;
[Property, Group( "Shape" )] public int Boulders { get; set; } = 60;
/// <summary>Floor radius round the middle kept free of stalagmites and boulders (the landing and the build sites).</summary>
[Property, Group( "Shape" )] public float ClearRadius { get; set; } = 1350f;
// ---- Mood -----------------------------------------------------------------------------------
[Property, Group( "Mood" )] public Color AmbientColor { get; set; } = new( 0.13f, 0.17f, 0.19f );
[Property, Group( "Mood" )] public Color FogColor { get; set; } = new( 0.008f, 0.02f, 0.024f );
[Property, Group( "Mood" )] public float FogStart { get; set; } = 500f;
[Property, Group( "Mood" )] public float FogEnd { get; set; } = 6500f;
[Property, Group( "Mood" )] public float FogHeight { get; set; } = 6000f;
/// <summary>Big glowing sacs hanging on roots from the roof: the cavern's main light.</summary>
[Property, Group( "Mood" )] public int GlowSacs { get; set; } = 9;
[Property, Group( "Mood" )] public float GlowSacRadius { get; set; } = 2600f;
/// <summary>Multiplies every bioluminescent light.</summary>
[Property, Group( "Mood" )] public float GlowBrightness { get; set; } = 1.4f;
[Property, Group( "Mood" )] public int FungusClumps { get; set; } = 14;
[Property, Group( "Mood" )] public int Pools { get; set; } = 6;
[Property, Group( "Mood" )] public int HangingRoots { get; set; } = 40;
// ---- Layout ---------------------------------------------------------------------------------
/// <summary>Hiding places (each gets a junk heap). There are 9 misfits; spares let them be picky.</summary>
[Property, Group( "Layout" ), Range( 12, 24 )] public int MisfitSpotCount { get; set; } = 16;
/// <summary>Boxes in each junk heap, at most.</summary>
[Property, Group( "Layout" )] public int JunkPerHeap { get; set; } = 9;
// ---- Shaft and arrival ----------------------------------------------------------------------
/// <summary>How far the shaft's stub hangs down from the roof, in inches.</summary>
[Property, Group( "Arrival" )] public float ShaftLength { get; set; } = 650f;
[Property, Group( "Arrival" )] public float ShaftRadius { get; set; } = 120f;
/// <summary>Seconds held in the dark shaft with the walls rushing past before the real fall.</summary>
[Property, Group( "Arrival" )] public float HoldSeconds { get; set; } = 1.8f;
/// <summary>Downward speed the real fall starts with, in inches a second.</summary>
[Property, Group( "Arrival" )] public float FallStartSpeed { get; set; } = 300f;
/// <summary>How hard the camera is knocked down on landing.</summary>
[Property, Group( "Arrival" )] public float LandKick { get; set; } = 34f;
[Property, Group( "Arrival" )] public string Title { get; set; } = "THE SUMP";
[Property, Group( "Arrival" )] public string TitleLine { get; set; } = "Miles down. Nobody conquers here. Nobody flushes, either.";
[Property, Group( "Arrival" )] public float CardSeconds { get; set; } = 4.5f;
[Property, Group( "Arrival" )] public string HubObjective { get; set; } = "Find the ones who hide here";
/// <summary>
/// The rule for how the lizard arrives, in order:
/// 1. Back from the surface (it left by the way up, see <see cref="CameFromSurface"/>): it
/// climbs down the rope.
/// 2. It has been in this Sump before (the save remembers the first landing, or somebody is
/// already healed): no fall, it wakes on the cushion.
/// 3. Otherwise, the first ever visit: the fall.
/// Turn this off and step 2 is skipped, so every visit that is not a climb down is the fall.
/// </summary>
[Property, Group( "Arrival" )] public bool ShortArrivalWhenReturning { get; set; } = true;
/// <summary>Always wake on the cushion, whatever the rule says (for testing the hub).</summary>
[Property, Group( "Arrival" )] public bool SkipArrival { get; set; }
/// <summary>Seconds the climb down the rope takes, and how far up it starts.</summary>
[Property, Group( "Arrival" )] public float RopeSeconds { get; set; } = 3.2f;
[Property, Group( "Arrival" )] public float RopeHeight { get; set; } = 620f;
/// <summary>
/// Set when the lizard leaves the Sump by the way up to the surface (<see cref="HubSurface"/>),
/// and used up by the next arrival, which is then the climb back down. Kept for the session
/// only: quit on the surface and the next visit is an ordinary waking on the cushion.
/// </summary>
public static bool CameFromSurface { get; set; }
/// <summary>The save's note that the first fall has been had.</summary>
const string ArrivedNote = "sump_arrived";
/// <summary>
/// Take the rock away by itself while the player is far from the cavern (a flashback, the
/// finale), and put it back when they return. Without this the lizard is dragged back inside.
/// </summary>
[Property, Group( "Arrival" )] public bool AutoHide { get; set; } = true;
// ---- State ----------------------------------------------------------------------------------
enum Phase { Waiting, Hold, Fall, Landed, Settle, Rope, Hub }
const string RockTag = "sumprock";
static readonly Color[] GlowPalette =
{
new( 0.15f, 0.9f, 0.75f ), // teal
new( 0.55f, 0.3f, 1f ), // violet
new( 0.45f, 1f, 0.3f ), // sick green
new( 0.2f, 0.5f, 1f ), // deep blue
new( 1f, 0.35f, 0.7f ), // pink
new( 0.1f, 0.8f, 1f ), // cyan
};
static readonly Color[] JunkPalette =
{
new( 0.42f, 0.32f, 0.2f ), // cardboard
new( 0.38f, 0.19f, 0.11f ), // rust
new( 0.62f, 0.64f, 0.62f ), // fridge white
new( 0.16f, 0.16f, 0.18f ), // dead television
new( 0.14f, 0.24f, 0.38f ), // blue crate
new( 0.5f, 0.12f, 0.1f ), // red plastic
new( 0.55f, 0.46f, 0.12f ), // yellow tub
};
sealed class Glow
{
public PointLight Light;
public Color Color;
public float Phase, Speed, Depth;
}
sealed class Streak
{
public GameObject Object;
public Vector3 Offset;
public float Start;
}
Phase _phase;
TimeSince _sincePhase;
TimeSince _sinceLanded;
int _frames;
bool _useTag = true;
bool _wasFar;
int _nextLine;
bool _cardShown;
ReptileController _player;
Random _rng;
GameObject _world; // everything except the rock: lights, fog, dressing
GameObject _rock; // the CaveGenerator's object
CaveGenerator _cave;
Material _material;
Vector3 _column; // where the fall comes down: the floor point under the shaft
Vector3 _fallTop; // feet position at the top of the fall
float _roofZ;
PointLight _cushionLight;
Color _cushionColor;
SoundHandle _wind;
readonly List<Glow> _glows = new();
readonly List<Streak> _streaks = new();
readonly List<(GameObject Object, Vector3 Scale)> _cushionFungus = new();
// Voices from the dark after the landing: seconds after landing, who, what.
static readonly (float At, string Who, string Text)[] ArrivalLines =
{
( 1.4f, "A voice in the dark", "...another one. It fell the whole way. It bounced." ),
( 4.8f, "A second voice", "Shh. It still smells of the crowd. And of whatever sat on it." ),
( 8.4f, "A voice in the dark", "Leave it be. They all come looking, in the end. And somebody put a leaf on its front." ),
};
// ---- Start ----------------------------------------------------------------------------------
protected override void OnStart()
{
if ( Scene.IsEditor ) return;
_instance = this;
Ready = false;
HubVisible = false;
_misfitSpots.Clear();
_buildSites.Clear();
SumpState.EnsureStarted();
_rng = new Random( unchecked(SumpState.Seed * 31 + 7) );
Centre = WorldPosition + CentreOffset;
FloorRadius = MathF.Min( Size.x, Size.y ) * 0.6f;
FinaleDoor = Centre;
// Black, and nothing moves, until the cavern is there.
Sump.Mode = SumpMode.Arrival;
Sump.Fade = 1f;
_player = Sump.Player;
if ( _player.IsValid() ) _player.InputLocked = true;
_material = Material.Load( RockMaterial );
_world = Sump.Spawn( "Sump Cavern", Centre, GameObject );
CreateRock();
BuildAtmosphere();
HubVisible = true;
_phase = Phase.Waiting;
_sincePhase = 0;
}
protected override void OnDestroy()
{
// Removed part-way through an arrival: the lizard is not left held, locked or in the dark.
if ( _phase != Phase.Hub )
{
if ( _player.IsValid() ) { _player.InputLocked = false; _player.Leash = null; _player.LeashRadius = 40f; }
if ( Sump.Mode == SumpMode.Arrival ) Sump.Fade = 0f;
}
if ( _wind.IsValid() ) _wind.Stop( 0.1f );
if ( _instance == this )
{
_instance = null;
Ready = false;
HubVisible = false;
}
}
/// <summary>
/// Makes the rock: one CaveGenerator with its renderer and collider. Built switched off and
/// then switched on, so the generator builds once with our settings rather than its defaults.
/// The same seed always gives the same cavern, so it can be thrown away and remade.
/// </summary>
void CreateRock()
{
if ( _rock.IsValid() ) return;
_rock = new GameObject( GameObject, false, "Sump Rock" );
_rock.Flags |= GameObjectFlags.NotSaved;
_rock.WorldPosition = Centre;
_rock.WorldRotation = Rotation.Identity;
_rock.Tags.Add( RockTag );
var renderer = _rock.Components.Create<ModelRenderer>();
var collider = _rock.Components.Create<ModelCollider>();
_cave = _rock.Components.Create<CaveGenerator>();
_cave.Renderer = renderer;
_cave.Collider = collider;
_cave.Material = _material;
_cave.Size = Size;
_cave.Seed = SumpState.Seed;
_cave.Detail = Math.Clamp( Detail, 3, 6 );
_cave.WallNoise = WallNoise;
_cave.WallDetail = WallDetail;
_cave.NoiseFrequency = NoiseFrequency;
_cave.FloorLevel = FloorLevel;
_cave.FloorBumpHeight = FloorBumpHeight;
_cave.TextureScale = TextureScale;
_cave.Stalactites = Stalactites;
_cave.Stalagmites = Stalagmites;
_cave.Boulders = Boulders;
_cave.SpawnClearRadius = ClearRadius;
_cave.HoleDirections = new List<Vector3>(); // sealed: no holes to the outside
_rock.Enabled = true;
}
/// <summary>Soft ambient so it is never pitch black, and fog that swallows the far walls.</summary>
void BuildAtmosphere()
{
var air = Sump.Spawn( "Sump Air", Centre, _world );
_airAmbient = air.Components.Create<AmbientLight>();
_airAmbient.Color = AmbientColor;
// FogHeight is not passed on: it was GradientFog's ceiling, far above the roof. See SumpFog.Create.
_airFog = SumpFog.Create( air, FogColor, FogStart, FogEnd );
}
// The cavern's own air. Switched off by hand with the hub (see ApplyVisible): a fog left to
// its disabled parent has been seen still fogging the finale on top of the finale's own.
AmbientLight _airAmbient;
Fog _airFog;
void SetAir( bool on )
{
if ( _airFog.IsValid() )
{
_airFog.FogEnabled = on;
_airFog.DistanceEnabled = on;
_airFog.Enabled = on;
}
if ( _airAmbient.IsValid() ) _airAmbient.Enabled = on;
}
// ---- Every frame ----------------------------------------------------------------------------
protected override void OnUpdate()
{
if ( Scene.IsEditor || !_world.IsValid() ) return;
_frames++;
if ( !_player.IsValid() ) _player = Sump.Player;
switch ( _phase )
{
case Phase.Waiting: UpdateWaiting(); break;
case Phase.Hold: UpdateHold(); break;
case Phase.Fall: UpdateFall(); break;
case Phase.Landed: UpdateLanded(); break;
case Phase.Settle: UpdateSettle(); break;
case Phase.Rope: UpdateRope(); break;
case Phase.Hub: UpdateHub(); break;
}
if ( HubVisible ) AnimateGlows();
}
protected override void OnFixedUpdate()
{
if ( Scene.IsEditor || !_player.IsValid() ) return;
// Nothing to stand on yet: keep the lizard where it is rather than let it fall in the dark.
if ( _phase == Phase.Waiting )
{
_waitPost ??= _player.WorldPosition;
_player.Leash = _waitPost;
_player.LeashRadius = 0.01f;
}
// Held at the top of the shaft. Same post as Sump.Teleport uses, so the two never fight.
else if ( _phase == Phase.Hold )
{
_player.Leash = _fallTop + Vector3.Up * _player.Radius;
_player.LeashRadius = 0.01f;
}
// On the rope: carried down it.
else if ( _phase == Phase.Rope )
{
_player.Leash = _ropeAt;
_player.LeashRadius = 0.01f;
}
}
Vector3? _waitPost;
/// <summary>Waits for the rock's collision to answer traces, then lays everything out.</summary>
void UpdateWaiting()
{
Sump.Fade = 1f;
if ( _frames < 4 || _sincePhase < 0.15f ) return;
if ( !RockAnswers() && _sincePhase < 2.5f ) return;
BuildLayout();
Ready = true;
BeginArrival();
}
/// <summary>True once a trace finds the cavern floor. Falls back to untagged traces if tags don't match.</summary>
bool RockAnswers()
{
float z = FormulaFloor( Centre.x, Centre.y );
var from = new Vector3( Centre.x, Centre.y, z + 300f );
var to = new Vector3( Centre.x, Centre.y, z - 500f );
if ( Scene.Trace.Ray( from, to ).WithTag( RockTag ).Run().Hit ) { _useTag = true; return true; }
if ( _sincePhase < 1.2f ) return false;
var trace = Scene.Trace.Ray( from, to );
if ( _player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( _player.GameObject );
if ( !trace.Run().Hit ) return false;
_useTag = false;
return true;
}
// ---- Traces and the floor -------------------------------------------------------------------
SceneTraceResult RockTrace( Vector3 from, Vector3 to, float radius = 0f )
{
var trace = radius > 0f ? Scene.Trace.Sphere( radius, from, to ) : Scene.Trace.Ray( from, to );
if ( _useTag ) trace = trace.WithTag( RockTag );
else if ( _player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( _player.GameObject );
return trace.Run();
}
/// <summary>The ground under (x, y): the traced rock if it is there, else the floor formula.</summary>
Vector3 FloorAt( float x, float y, out Vector3 normal )
{
float z = FormulaFloor( x, y );
normal = Vector3.Up;
if ( !HubVisible || !_rock.IsValid() ) return new Vector3( x, y, z );
var tr = RockTrace( new Vector3( x, y, z + 350f ), new Vector3( x, y, z - 500f ) );
if ( !tr.Hit || tr.StartedSolid ) return new Vector3( x, y, z );
normal = tr.Normal;
return tr.HitPosition;
}
/// <summary>The cavern floor as CaveGenerator shapes it (same noise, same seeds), in world height.</summary>
float FormulaFloor( float x, float y )
{
var fp = new Vector3( x - Centre.x, y - Centre.y, 0f );
int seed = SumpState.Seed;
return Centre.z + FloorLevel * Size.z
+ FloorBumpHeight * Fbm( fp / 900f, 3, seed + 101 )
+ FloorBumpHeight * 0.3f * Fbm( fp / 180f, 2, seed + 202 );
}
/// <summary>Height above the floor's base level that clears every rise, for level probes across the cavern.</summary>
float ProbeZ => Centre.z + FloorLevel * Size.z + FloorBumpHeight * 1.3f + 160f;
/// <summary>How far the open floor runs from the centre in a direction before rock is in the way.</summary>
float ReachToward( float angle )
{
var dir = new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f );
var from = Centre.WithZ( ProbeZ );
float far = MathF.Max( Size.x, Size.y ) * 1.7f;
float fallback = new Vector2( dir.x * Size.x, dir.y * Size.y ).Length * 0.6f;
var tr = RockTrace( from, from + dir * far );
if ( !tr.Hit || tr.StartedSolid ) return fallback;
return MathF.Max( tr.Distance, 400f );
}
/// <summary>Height of the roof (or whatever hangs from it) over a floor point.</summary>
float CeilingOver( Vector3 floor, float radius = 0f )
{
float top = Centre.z + Size.z * 1.7f;
float fallback = Centre.z + Size.z * MathF.Max( 1f - WallNoise - WallDetail, 0.3f ) * 0.7f;
var from = floor + Vector3.Up * (250f + radius);
var tr = RockTrace( from, floor.WithZ( top ), radius );
if ( !tr.Hit || tr.StartedSolid ) return fallback;
return radius > 0f ? tr.EndPosition.z + radius : tr.HitPosition.z;
}
float R( float a, float b ) => a + (float)_rng.NextDouble() * (b - a);
Color Pick( Color[] palette ) => palette[_rng.Next( palette.Length )];
// ---- Layout ---------------------------------------------------------------------------------
/// <summary>
/// Finds the fall column, then builds the shaft, the landing cushion and all the dressing,
/// and fills the published lists. Runs once, when the rock's collision can be traced.
/// </summary>
void BuildLayout()
{
PickColumn();
BuildShaft();
BuildCushion();
BuildSitesRing();
BuildEdges();
BuildGlowSacs();
BuildFungusAndPools();
BuildRoots();
Sump.HubSpawn = _column;
}
/// <summary>
/// Chooses where the fall comes down: near the middle, under the highest clear piece of roof,
/// so no stalactite is in the way of the shaft or the drop.
/// </summary>
void PickColumn()
{
float bestRoof = float.MinValue;
var best = FloorAt( Centre.x, Centre.y, out _ );
for ( int i = 0; i < 9; i++ )
{
float angle = i * MathF.PI * 2f / 8f;
float reach = i == 0 ? 0f : 260f;
var floor = FloorAt( Centre.x + MathF.Cos( angle ) * reach, Centre.y + MathF.Sin( angle ) * reach, out _ );
float roof = CeilingOver( floor, ShaftRadius + 30f );
if ( roof <= bestRoof ) continue;
bestRoof = roof;
best = floor;
}
_column = best;
_roofZ = bestRoof;
// The wide probe stops where it first touches the roof, so the roof over the very middle
// is at least this high. Start well under it, so the lizard is safely inside the shell.
_fallTop = _column.WithZ( MathF.Max( _roofZ - 140f, _column.z + 400f ) );
}
/// <summary>
/// The last piece of the shaft from the stadium: a rough tube of rock slabs that comes through
/// the roof and hangs down into the cavern. The lizard starts inside it, just under the roof.
/// </summary>
void BuildShaft()
{
var shaft = Sump.Spawn( "Shaft", _fallTop, _world );
var rockTint = new Color( 0.12f, 0.115f, 0.11f );
const int sides = 8, tiers = 4;
float top = _roofZ + 320f;
float bottom = _roofZ - ShaftLength;
float tierHeight = (top - bottom) / tiers;
for ( int t = 0; t < tiers; t++ )
{
// Each tier is a little wider or narrower and turned, so it reads as rough-cut rock.
float radius = ShaftRadius + R( -6f, 22f );
float turn = R( 0f, 45f );
float thick = R( 34f, 60f );
float width = 2f * (radius + thick) * MathF.Tan( MathF.PI / sides ) * 1.08f;
float z = bottom + tierHeight * (t + 0.5f);
for ( int s = 0; s < sides; s++ )
{
float yaw = turn + s * 360f / sides;
var outward = Rotation.FromYaw( yaw ).Forward;
var slab = Sump.Box( shaft, "Shaft Rock", _column.WithZ( z ) + outward * (radius + thick * 0.5f),
new Vector3( thick, width, tierHeight + 14f ), rockTint * R( 0.8f, 1.15f ) );
slab.WorldRotation = Rotation.FromYaw( yaw );
}
}
// The last grey of the world above, a long way up.
AddGlow( shaft, "Shaft Light", _fallTop + Vector3.Up * 60f, new Color( 0.55f, 0.62f, 0.75f ), 520f, 0.5f, 0.1f );
// Dust and grit rushing up past the lizard while it falls.
for ( int i = 0; i < 30; i++ )
{
float angle = R( 0f, MathF.PI * 2f );
float reach = R( 40f, ShaftRadius - 14f );
var streak = Sump.Box( shaft, "Dust Streak", _fallTop, new Vector3( 1.6f, 1.6f, R( 50f, 170f ) ),
new Color( 0.5f, 0.55f, 0.6f ) * R( 0.5f, 1f ), false );
_streaks.Add( new Streak
{
Object = streak,
Offset = new Vector3( MathF.Cos( angle ) * reach, MathF.Sin( angle ) * reach, 0f ),
Start = R( 0f, 1f ),
} );
}
}
/// <summary>The deep cushion the lizard lands on: dumped mattresses overgrown with glowing fungus.</summary>
void BuildCushion()
{
var cushion = Sump.Spawn( "Landing Cushion", _column, _world );
// Three sagging layers, the bottom one sunk well into the bumpy floor.
(Vector3 Size, Color Tint)[] layers =
{
( new Vector3( 300f, 250f, 70f ), new Color( 0.3f, 0.27f, 0.22f ) ),
( new Vector3( 250f, 205f, 26f ), new Color( 0.36f, 0.33f, 0.3f ) ),
( new Vector3( 200f, 170f, 22f ), new Color( 0.26f, 0.3f, 0.27f ) ),
};
float z = _column.z - 40f;
foreach ( var layer in layers )
{
var box = Sump.Box( cushion, "Mattress", _column.WithZ( z + layer.Size.z * 0.5f ), layer.Size, layer.Tint );
box.WorldRotation = Rotation.FromYaw( R( -14f, 14f ) );
z += layer.Size.z;
}
// The top of the pile is where the lizard lands, and where the hub is entered from then on.
_column = _column.WithZ( z + 0.5f );
// Fungus crowding round it. These have no collision; they squash when the lizard hits.
_cushionColor = GlowPalette[0];
for ( int i = 0; i < 22; i++ )
{
float angle = R( 0f, MathF.PI * 2f );
float reach = R( 150f, 290f );
var at = FloorAt( _column.x + MathF.Cos( angle ) * reach, _column.y + MathF.Sin( angle ) * reach, out _ );
float size = R( 16f, 44f );
var tint = Color.Lerp( _cushionColor, Pick( GlowPalette ), R( 0f, 0.5f ) );
var cap = Sump.Ball( cushion, "Fungus", at + Vector3.Up * size * 0.25f, new Vector3( size, size, size * R( 0.45f, 0.8f ) ), tint );
_cushionFungus.Add( (cap, cap.WorldScale) );
}
var glow = AddGlow( cushion, "Cushion Glow", _column + Vector3.Up * 150f, _cushionColor, 900f, 0.8f, 0.12f );
_cushionLight = glow.Light;
}
/// <summary>Flat clear spots in two rings round the landing: where the hub will build itself.</summary>
void BuildSitesRing()
{
AddSites( 6, 520f, 0f );
AddSites( 8, 940f, MathF.PI / 8f );
}
void AddSites( int count, float radius, float turn )
{
for ( int i = 0; i < count; i++ )
{
float angle = turn + i * MathF.PI * 2f / count;
var best = Vector3.Zero;
float bestFlat = -1f;
// Nudge round the ring and in and out until the ground is close to level.
foreach ( var (da, dr) in new[] { (0f, 0f), (0.14f, 0f), (-0.14f, 0f), (0f, -90f), (0f, 90f), (0.22f, -60f), (-0.22f, 60f) } )
{
float a = angle + da, r = radius + dr;
var at = FloorAt( _column.x + MathF.Cos( a ) * r, _column.y + MathF.Sin( a ) * r, out var normal );
if ( normal.z <= bestFlat ) continue;
bestFlat = normal.z;
best = at;
if ( normal.z > 0.97f ) break;
}
_buildSites.Add( best );
}
}
/// <summary>
/// Works round the cavern's edge: a hiding place every so often with a heap of human junk
/// between it and the middle, and the lowest point of the rim for the finale's door.
/// </summary>
void BuildEdges()
{
var edges = Sump.Spawn( "Edges", Centre, _world );
int count = Math.Clamp( MisfitSpotCount, 12, 24 );
float turn = R( 0f, MathF.PI * 2f );
float reachSum = 0f;
for ( int i = 0; i < count; i++ )
{
float angle = turn + (i + R( -0.25f, 0.25f )) * MathF.PI * 2f / count;
float reach = ReachToward( angle );
reachSum += reach;
var dir = new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f );
// Tuck the hiding place in near the wall, but always outside the build sites.
float spotReach = MathF.Max( reach * R( 0.76f, 0.84f ), MathF.Min( ClearRadius + 150f, reach * 0.9f ) );
var spot = FloorAt( Centre.x + dir.x * spotReach, Centre.y + dir.y * spotReach, out _ );
_misfitSpots.Add( spot );
// The heap stands between the spot and the middle of the cavern.
var heapAt = FloorAt( spot.x - dir.x * 230f, spot.y - dir.y * 230f, out _ );
BuildJunkHeap( edges, heapAt, i );
// A little fungus by every other one, so the hiding places can just be made out.
if ( i % 2 == 0 )
{
var side = new Vector3( -dir.y, dir.x, 0f ) * (R( 0f, 1f ) < 0.5f ? 150f : -150f);
BuildFungusClump( edges, FloorAt( spot.x + side.x, spot.y + side.y, out _ ), Pick( GlowPalette ), 420f );
}
}
FloorRadius = reachSum / count;
// The lowest stretch of the rim is where the way down will open.
float lowest = float.MaxValue;
for ( int i = 0; i < 24; i++ )
{
float angle = i * MathF.PI * 2f / 24f;
float reach = ReachToward( angle ) * 0.9f;
var at = FloorAt( Centre.x + MathF.Cos( angle ) * reach, Centre.y + MathF.Sin( angle ) * reach, out var normal );
if ( normal.z < 0.6f || at.z >= lowest ) continue;
lowest = at.z;
FinaleDoor = at;
}
if ( lowest == float.MaxValue && _misfitSpots.Count > 0 ) FinaleDoor = _misfitSpots[0];
BuildDoorMarker( edges );
}
/// <summary>A heap of what people throw away: a ring of boxes on the ground and a few stacked on top.</summary>
void BuildJunkHeap( GameObject parent, Vector3 at, int index )
{
var heap = Sump.Spawn( $"Junk Heap {index + 1}", at, parent );
int total = Math.Max( _rng.Next( JunkPerHeap / 2, JunkPerHeap + 1 ), 4 );
int stacked = Math.Min( total / 3, 3 );
int around = total - stacked;
for ( int i = 0; i < around; i++ )
{
float angle = i * MathF.PI * 2f / around + R( -0.3f, 0.3f );
float reach = R( 55f, 125f );
var size = new Vector3( R( 34f, 95f ), R( 30f, 80f ), R( 26f, 90f ) );
var ground = FloorAt( at.x + MathF.Cos( angle ) * reach, at.y + MathF.Sin( angle ) * reach, out _ );
var box = Sump.Box( heap, "Junk", ground + Vector3.Up * (size.z * 0.5f - 7f), size, Pick( JunkPalette ) * R( 0.7f, 1f ) );
box.WorldRotation = new Angles( R( -7f, 7f ), R( 0f, 360f ), R( -7f, 7f ) ).ToRotation();
}
float z = at.z - 8f;
for ( int i = 0; i < stacked; i++ )
{
var size = new Vector3( R( 80f, 120f ), R( 70f, 105f ), R( 40f, 75f ) ) * (1f - i * 0.2f);
var box = Sump.Box( heap, "Junk", at.WithZ( z + size.z * 0.5f ), size, Pick( JunkPalette ) * R( 0.7f, 1f ) );
box.WorldRotation = Rotation.FromYaw( R( 0f, 360f ) );
z += size.z;
}
}
/// <summary>Marks the finale's door: a sealed lintel of fallen rock with something red breathing under it.</summary>
void BuildDoorMarker( GameObject parent )
{
var door = Sump.Spawn( "Way Down (sealed)", FinaleDoor, parent );
var outward = (FinaleDoor - Centre).WithZ( 0f );
float yaw = outward.Length > 1f ? MathF.Atan2( outward.y, outward.x ) * 180f / MathF.PI : 0f;
var rot = Rotation.FromYaw( yaw );
var tint = new Color( 0.1f, 0.09f, 0.09f );
Sump.Box( door, "Door Post", FinaleDoor + rot.Left * 95f + Vector3.Up * 70f, new Vector3( 55f, 50f, 190f ), tint ).WorldRotation = rot;
Sump.Box( door, "Door Post", FinaleDoor + rot.Right * 95f + Vector3.Up * 70f, new Vector3( 55f, 50f, 190f ), tint ).WorldRotation = rot;
Sump.Box( door, "Door Lintel", FinaleDoor + Vector3.Up * 185f, new Vector3( 65f, 270f, 50f ), tint ).WorldRotation = rot * Rotation.FromRoll( 4f );
AddGlow( door, "Door Glow", FinaleDoor + Vector3.Up * 60f, new Color( 0.9f, 0.12f, 0.08f ), 520f, 0.35f, 0.45f, 0.5f );
}
/// <summary>The cavern's main light: fat glowing sacs hanging on long roots from the roof.</summary>
void BuildGlowSacs()
{
var sacs = Sump.Spawn( "Glow Sacs", Centre, _world );
float turn = R( 0f, MathF.PI * 2f );
for ( int i = 0; i < GlowSacs; i++ )
{
float angle = turn + (i + R( -0.3f, 0.3f )) * MathF.PI * 2f / Math.Max( GlowSacs, 1 );
float reach = ReachToward( angle ) * R( 0.3f, 0.62f );
var floor = FloorAt( Centre.x + MathF.Cos( angle ) * reach, Centre.y + MathF.Sin( angle ) * reach, out _ );
float roof = CeilingOver( floor );
float height = MathF.Min( R( 450f, 1100f ), (roof - floor.z) * 0.6f );
var at = floor + Vector3.Up * height;
var color = GlowPalette[i % GlowPalette.Length];
float size = R( 45f, 80f );
Sump.Ball( sacs, "Glow Sac", at, new Vector3( size, size, size * 1.25f ), color );
Sump.Ball( sacs, "Glow Sac Bud", at + new Vector3( size * 0.7f, 0f, size * 0.6f ), new Vector3( size, size, size ) * 0.45f, color );
// The root it hangs from, up into the roof.
float rootLength = roof - at.z + 30f;
if ( rootLength > 10f )
Sump.Box( sacs, "Sac Root", at + Vector3.Up * rootLength * 0.5f, new Vector3( 9f, 9f, rootLength ), new Color( 0.12f, 0.1f, 0.07f ), false );
AddGlow( sacs, "Sac Light", at + Vector3.Down * (size * 1.25f + 30f), color, GlowSacRadius, 1f, 0.18f );
}
}
/// <summary>Fungus clumps and still glowing pools scattered over the floor, outside the build sites.</summary>
void BuildFungusAndPools()
{
var growth = Sump.Spawn( "Growth", Centre, _world );
for ( int i = 0; i < FungusClumps; i++ )
BuildFungusClump( growth, ScatterSpot(), Pick( GlowPalette ), i % 3 == 0 ? 480f : 0f );
for ( int i = 0; i < Pools; i++ )
{
var at = ScatterSpot();
var color = i % 2 == 0 ? GlowPalette[5] : GlowPalette[0];
float size = R( 110f, 240f );
Sump.Ball( growth, "Pool", at + Vector3.Down * 2f, new Vector3( size, size * R( 0.6f, 1f ), 7f ), color * 0.7f ).WorldRotation = Rotation.FromYaw( R( 0f, 180f ) );
AddGlow( growth, "Pool Light", at + Vector3.Up * 70f, color, 650f, 0.55f, 0.25f, 0.6f );
}
}
/// <summary>A random floor point between the build sites and the walls.</summary>
Vector3 ScatterSpot()
{
float angle = R( 0f, MathF.PI * 2f );
float reach = ReachToward( angle );
float r = Math.Clamp( reach * R( 0.4f, 0.8f ), MathF.Min( ClearRadius + 100f, reach * 0.85f ), reach * 0.85f );
return FloorAt( Centre.x + MathF.Cos( angle ) * r, Centre.y + MathF.Sin( angle ) * r, out _ );
}
/// <summary>A few glowing caps on stalks. Give a light radius to make it light the ground round it.</summary>
void BuildFungusClump( GameObject parent, Vector3 at, Color color, float lightRadius )
{
var clump = Sump.Spawn( "Fungus Clump", at, parent );
int caps = _rng.Next( 3, 7 );
for ( int i = 0; i < caps; i++ )
{
var offset = new Vector3( R( -55f, 55f ), R( -55f, 55f ), 0f );
float tall = R( 12f, 70f );
float size = R( 9f, 26f );
var foot = FloorAt( at.x + offset.x, at.y + offset.y, out _ );
Sump.Box( clump, "Stalk", foot + Vector3.Up * tall * 0.5f, new Vector3( size * 0.3f, size * 0.3f, tall ), color * 0.25f, false );
Sump.Ball( clump, "Cap", foot + Vector3.Up * tall, new Vector3( size, size, size * 0.55f ), color );
}
if ( lightRadius > 0f )
AddGlow( clump, "Fungus Light", at + Vector3.Up * 55f, color, lightRadius, 0.5f, 0.3f, 0.9f );
}
/// <summary>Roots of whatever grows far above, hanging in ropes from the roof.</summary>
void BuildRoots()
{
var roots = Sump.Spawn( "Roots", Centre, _world );
var tint = new Color( 0.13f, 0.1f, 0.07f );
for ( int i = 0; i < HangingRoots; i++ )
{
float angle = R( 0f, MathF.PI * 2f );
float reach = ReachToward( angle ) * R( 0.15f, 0.85f );
var floor = FloorAt( Centre.x + MathF.Cos( angle ) * reach, Centre.y + MathF.Sin( angle ) * reach, out _ );
// Keep the fall clear.
if ( (floor - _column).WithZ( 0f ).Length < ShaftRadius + 120f ) continue;
float roof = CeilingOver( floor );
float room = roof - floor.z;
if ( room < 300f ) continue;
// Three lengths, each wandering a little off the last and getting thinner.
var from = floor.WithZ( roof + 20f );
float thick = R( 6f, 15f );
float length = MathF.Min( R( 200f, 800f ), room * 0.6f ) / 3f;
for ( int s = 0; s < 3; s++ )
{
var dir = (Vector3.Down + new Vector3( R( -0.16f, 0.16f ), R( -0.16f, 0.16f ), 0f )).Normal;
var piece = Sump.Box( roots, "Root", from + dir * length * 0.5f, new Vector3( length + thick, thick, thick ), tint * R( 0.8f, 1.2f ), false );
piece.WorldRotation = Rotation.LookAt( dir, Vector3.Forward );
from += dir * length;
thick *= 0.7f;
}
}
}
/// <summary>A bioluminescent point light that slowly breathes.</summary>
Glow AddGlow( GameObject parent, string name, Vector3 at, Color color, float radius, float strength, float depth, float speed = 0.35f )
{
var go = Sump.Spawn( name, at, parent );
var light = go.Components.Create<PointLight>();
light.Radius = radius;
light.Shadows = false;
var glow = new Glow
{
Light = light,
Color = color * strength,
Depth = depth,
Speed = speed * R( 0.7f, 1.3f ),
Phase = R( 0f, MathF.PI * 2f ),
};
light.LightColor = (glow.Color * GlowBrightness).WithAlpha( 1f );
_glows.Add( glow );
return glow;
}
void AnimateGlows()
{
float now = Time.Now;
float flash = 0f;
if ( _phase is Phase.Landed or Phase.Hub && _sinceLanded < 1.2f ) flash = (1f - _sinceLanded / 1.2f) * 2.5f;
foreach ( var glow in _glows )
{
if ( !glow.Light.IsValid() ) continue;
float breath = 1f - glow.Depth * (0.5f + 0.5f * MathF.Sin( now * glow.Speed + glow.Phase ));
if ( glow.Light == _cushionLight ) breath += flash;
glow.Light.LightColor = (glow.Color * (GlowBrightness * breath)).WithAlpha( 1f );
}
}
// ---- The arrival ----------------------------------------------------------------------------
/// <summary>True if this lizard has been in this Sump before (see <see cref="ShortArrivalWhenReturning"/>).</summary>
bool Returning => SkipArrival
|| (ShortArrivalWhenReturning && (SumpState.GetNote( ArrivedNote ) == "1" || SumpState.HealedCount > 0));
GameObject _rope;
Vector3 _ropeTop, _ropeAt;
void BeginArrival()
{
_waitPost = null;
// Back from the surface: down the rope it went up. (Used up here, whichever way this goes.)
bool fromSurface = CameFromSurface && !SkipArrival;
CameFromSurface = false;
if ( fromSurface )
{
ClearStreaks();
float room = MathF.Max( _roofZ - 160f - _column.z, 120f );
_ropeTop = _column + Vector3.Up * Math.Clamp( RopeHeight, 120f, room );
_ropeAt = _ropeTop;
// The rope itself: something to be seen coming down. Not solid.
float length = _roofZ + 200f - _column.z;
_rope = Sump.Box( _world, "Rope", _column + Vector3.Up * (length * 0.5f) + Vector3.Forward * 14f, new Vector3( 2.5f, 2.5f, length ), new Color( 0.3f, 0.24f, 0.15f ), false );
Sump.Teleport( _ropeTop, 0f );
if ( _player.IsValid() ) _player.SetLook( new Angles( 40f, 0f, 0f ) );
SetPhase( Phase.Rope );
return;
}
if ( Returning )
{
// Been here before: no fall, just wake up on the cushion.
ClearStreaks();
if ( _player.IsValid() ) { _player.Leash = null; _player.LeashRadius = 40f; } // the wait is over: let go
Sump.Teleport( _column, 0f );
SetPhase( Phase.Settle );
return;
}
Sump.Teleport( _fallTop, 0f );
if ( _player.IsValid() ) _player.SetLook( new Angles( 35f, 0f, 0f ) );
_wind = Sump.Sfx( "shaft_wind", _fallTop, 0.9f );
SetPhase( Phase.Hold );
}
void SetPhase( Phase phase )
{
_phase = phase;
_sincePhase = 0;
}
/// <summary>Held in the shaft: still black, the screen clearing, grit tearing past.</summary>
void UpdateHold()
{
float hold = MathF.Max( HoldSeconds, 0.3f );
Sump.Fade = 1f - 0.8f * Math.Clamp( _sincePhase / hold, 0f, 1f );
if ( _player.IsValid() ) _player.InputLocked = true;
MoveStreaks();
if ( _sincePhase < hold ) return;
// Let go. It leaves the shaft already moving.
if ( _player.IsValid() )
{
_player.Leash = null;
_player.LeashRadius = 40f;
_player.Lunge( Vector3.Down, FallStartSpeed );
}
SetPhase( Phase.Fall );
}
/// <summary>The real fall, under the lizard's own gravity, out of the shaft and down through the cavern.</summary>
void UpdateFall()
{
Sump.Fade = MathF.Max( Sump.Fade - Time.Delta * 0.5f, 0f );
MoveStreaks();
bool landed;
if ( _player.IsValid() )
{
_player.InputLocked = true;
float above = _player.WorldPosition.z - _column.z;
landed = _sincePhase > 0.3f && (_player.Attached || above < 4f);
// Caught on something on the way down, or never arrived: put it on the cushion.
if ( (landed && above > 120f) || _sincePhase > 8f )
{
Sump.Teleport( _column, 0f );
landed = true;
}
}
else landed = _sincePhase > 3f;
if ( landed ) Land();
}
void Land()
{
ClearStreaks();
if ( _wind.IsValid() ) _wind.Stop( 0.4f );
Sump.Sfx( "landing", _column, 1f );
if ( _player.IsValid() ) _player.Kick( Vector3.Down * LandKick );
_sinceLanded = 0;
_nextLine = 0;
SumpState.SetNote( ArrivedNote, "1" ); // the fall is had once; after this it wakes on the cushion
SetPhase( Phase.Landed );
}
/// <summary>Lying winded on the cushion: fungus settles, the title comes up, then the hub begins.</summary>
void UpdateLanded()
{
Sump.Fade = MathF.Max( Sump.Fade - Time.Delta * 0.8f, 0f );
SquashCushion();
SpeakArrivalLines();
if ( !_cardShown && _sincePhase > 0.8f )
{
_cardShown = true;
Sump.CardTitle = Title;
Sump.CardLine = TitleLine;
Sump.Sfx( "title_sting", _column, 0.8f );
}
if ( _sincePhase < 0.8f + CardSeconds ) return;
Sump.CardTitle = "";
Sump.CardLine = "";
EnterHub();
}
/// <summary>The short arrival: fade up already on the cushion.</summary>
void UpdateSettle()
{
Sump.Fade = 1f - Math.Clamp( (_sincePhase - 0.3f) / 1.5f, 0f, 1f );
if ( _player.IsValid() ) _player.InputLocked = true;
if ( _sincePhase < 1.8f ) return;
_sinceLanded = 100f;
_nextLine = ArrivalLines.Length;
SumpState.SetNote( ArrivedNote, "1" ); // (a save from before this note existed)
EnterHub();
}
/// <summary>Back from the surface: lowered hand under hand down the rope onto the cushion.</summary>
void UpdateRope()
{
float seconds = MathF.Max( RopeSeconds, 0.5f );
float t = Math.Clamp( _sincePhase / seconds, 0f, 1f );
Sump.Fade = 1f - Math.Clamp( (_sincePhase - 0.2f) / 1f, 0f, 1f );
if ( _player.IsValid() ) _player.InputLocked = true;
// Steady, with a soft start and stop. OnFixedUpdate holds the lizard at this point.
float eased = t * t * (3f - 2f * t);
_ropeAt = Vector3.Lerp( _ropeTop, _column, eased );
if ( t < 1f ) return;
if ( _player.IsValid() ) { _player.Leash = null; _player.LeashRadius = 40f; }
Sump.Teleport( _column, 0f );
if ( _rope.IsValid() ) _rope.Destroy();
_rope = null;
Sump.Sfx( "landing", _column, 0.5f );
Sump.Say( "A voice in the dark", "It came back. It smells of up there. Wipe your feet." );
_sinceLanded = 100f;
_nextLine = ArrivalLines.Length;
SumpState.SetNote( ArrivedNote, "1" );
EnterHub();
}
void EnterHub()
{
Sump.Fade = 0f;
if ( Sump.Mode == SumpMode.Arrival ) Sump.Mode = SumpMode.Hub;
if ( string.IsNullOrEmpty( Sump.Objective ) ) Sump.Objective = HubObjective;
if ( _player.IsValid() ) _player.InputLocked = false;
SetPhase( Phase.Hub );
}
void UpdateHub()
{
// The last of the voices may still be due after the controls come back.
if ( Sump.Mode == SumpMode.Hub ) SpeakArrivalLines();
if ( _sinceLanded < 2f ) SquashCushion();
// Away in a flashback or the finale the rock has to go, or the lizard is dragged back
// inside it. It returns when the lizard does.
if ( !AutoHide || !_player.IsValid() ) return;
float away = (_player.WorldPosition - Centre).Length;
bool far = away > MathF.Max( Size.x, MathF.Max( Size.y, Size.z ) ) * 2f + 3000f;
if ( far == _wasFar ) return;
_wasFar = far;
ApplyVisible( !far );
}
void SpeakArrivalLines()
{
while ( _nextLine < ArrivalLines.Length && _sinceLanded > ArrivalLines[_nextLine].At )
{
var line = ArrivalLines[_nextLine++];
Sump.Say( line.Who, line.Text );
}
}
/// <summary>The fungus round the cushion flattens under the impact and springs slowly back.</summary>
void SquashCushion()
{
float t = Math.Clamp( _sinceLanded / 1.6f, 0f, 1f );
float squash = MathF.Sin( t * MathF.PI ) * (1f - t) * 0.9f;
foreach ( var (cap, scale) in _cushionFungus )
{
if ( !cap.IsValid() ) continue;
cap.WorldScale = new Vector3( scale.x * (1f + squash * 0.35f), scale.y * (1f + squash * 0.35f), scale.z * (1f - squash * 0.6f) );
}
}
/// <summary>Keeps the grit streaming upward round the lizard, wrapping from above its head to below its feet.</summary>
void MoveStreaks()
{
if ( _streaks.Count == 0 ) return;
var around = _player.IsValid() ? _player.WorldPosition : _fallTop;
const float span = 760f, speed = 1500f;
foreach ( var streak in _streaks )
{
if ( !streak.Object.IsValid() ) continue;
float along = (streak.Start * span + Time.Now * speed) % span;
streak.Object.WorldPosition = around + streak.Offset + Vector3.Up * (along - span * 0.5f);
}
}
void ClearStreaks()
{
foreach ( var streak in _streaks )
if ( streak.Object.IsValid() ) streak.Object.Destroy();
_streaks.Clear();
}
// ---- Hiding the hub -------------------------------------------------------------------------
void ApplyVisible( bool visible )
{
if ( visible == HubVisible ) return;
HubVisible = visible;
// Fog and ambient go off before their parent does, and come back on after it, so each
// is told while it can still act on it.
if ( !visible ) SetAir( false );
if ( _world.IsValid() ) _world.Enabled = visible;
if ( visible ) SetAir( true );
// The rock is only switched off, not rebuilt: the lizard is let out of it by the
// controller (StayInCaves) while it is away, so coming back costs nothing.
if ( _rock.IsValid() ) _rock.Enabled = visible;
else if ( visible ) CreateRock();
}
// ---- Noise (the same as CaveGenerator's, so the floor formula matches its floor) -------------
static float Fbm( Vector3 p, int octaves, int seed )
{
float sum = 0, amp = 0.5f, norm = 0;
for ( int o = 0; o < octaves; o++ )
{
sum += amp * ValueNoise( p, seed + o * 31 );
norm += amp;
p *= 2.03f;
amp *= 0.5f;
}
return sum / norm;
}
static float ValueNoise( Vector3 p, int seed )
{
int x0 = (int)MathF.Floor( p.x ), y0 = (int)MathF.Floor( p.y ), z0 = (int)MathF.Floor( p.z );
float fx = Smooth( p.x - x0 ), fy = Smooth( p.y - y0 ), fz = Smooth( p.z - z0 );
float Lerp( float a, float b, float f ) => a + (b - a) * f;
float Corner( int dx, int dy, int dz ) => Hash( x0 + dx, y0 + dy, z0 + dz, seed );
return Lerp(
Lerp( Lerp( Corner( 0, 0, 0 ), Corner( 1, 0, 0 ), fx ), Lerp( Corner( 0, 1, 0 ), Corner( 1, 1, 0 ), fx ), fy ),
Lerp( Lerp( Corner( 0, 0, 1 ), Corner( 1, 0, 1 ), fx ), Lerp( Corner( 0, 1, 1 ), Corner( 1, 1, 1 ), fx ), fy ),
fz );
}
static float Smooth( float f ) => f * f * (3f - 2f * f);
static float Hash( int x, int y, int z, int seed )
{
unchecked
{
uint h = (uint)(x * 374761393 + y * 668265263 + z * 1440662683 + seed * 2246822519u);
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
return (h & 0xFFFFFF) / (float)0xFFFFFF * 2f - 1f;
}
}
}