Story/AsteroidSky.cs

Component that builds the sky outside a hollow asteroid: one spotlight per cave hole aimed along a moving sun direction, an Earth sprite revealed at orbit capture, and a spin that eases down when StoryDirector reaches the Captured stage.

using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// The sky outside the asteroid, as seen from inside it. Sunlight comes in through the holes in
/// the shell as beams: one spotlight per hole, parked just outside the rock and aimed along the
/// sun's direction, so light only ever exists where it comes through a hole. The asteroid spins,
/// so the beams sweep around the cave; they brighten as the asteroid nears Earth; and once the
/// story reaches orbit capture the spin slows right down and Earth shows through the first hole.
/// Goes on its own scene object. Only runs while playing.
/// </summary>
[Title( "Asteroid Sky" ), Category( "Story" ), Icon( "public" )]
public sealed class AsteroidSky : Component
{
	// ---- Sun ----------------------------------------------------------------------------------

	/// <summary>Tint of the sunlight: slightly warm white.</summary>
	[Property, Group( "Sun" )] public Color SunColor { get; set; } = new Color( 1f, 0.95f, 0.85f );

	/// <summary>Beam brightness when play starts, far from Earth.</summary>
	[Property, Group( "Sun" )] public float StartBrightness { get; set; } = 8f;

	/// <summary>Beam brightness once the approach is over.</summary>
	[Property, Group( "Sun" )] public float PeakBrightness { get; set; } = 30f;

	/// <summary>Seconds for the brightness to climb from start to peak.</summary>
	[Property, Group( "Sun" )] public float RampSeconds { get; set; } = 180f;

	/// <summary>How strongly the beams light the volumetric fog. This is what makes the shafts visible.</summary>
	[Property, Group( "Sun" )] public float FogStrength { get; set; } = 2.5f;

	/// <summary>How far outside the shell each beam's light sits, in inches.</summary>
	[Property, Group( "Sun" )] public float BeamOffset { get; set; } = 220f;

	/// <summary>Half-angle of each beam's cone, in degrees. Roughly hole radius over BeamOffset.</summary>
	[Property, Group( "Sun" )] public float BeamAngle { get; set; } = 6f;

	/// <summary>
	/// How close to straight overhead the sun must be before a beam appears (1 = dead overhead).
	/// High values make the beam rarer and shorter: one pass per turn of the asteroid.
	/// </summary>
	[Property, Group( "Sun" ), Range( 0.1f, 0.98f )] public float BeamWindow { get; set; } = 0.86f;

	/// <summary>Seconds of pure darkness before the first beam reaches full strength straight down.</summary>
	[Property, Group( "Sun" )] public float FirstBeamSeconds { get; set; } = 38f;

	/// <summary>How far each beam reaches into the cave, in inches.</summary>
	[Property, Group( "Sun" )] public float BeamReach { get; set; } = 4500f;

	// ---- Spin ---------------------------------------------------------------------------------

	/// <summary>Axis the asteroid spins about. Tilted off Z so beams cross walls as well as floor.</summary>
	[Property, Group( "Spin" )] public Vector3 SpinAxis { get; set; } = new Vector3( 1f, 0.15f, 0f );

	/// <summary>Spin speed while drifting.</summary>
	[Property, Group( "Spin" )] public float SpinDegreesPerSecond { get; set; } = 3f;

	/// <summary>Spin speed after the asteroid has been captured into orbit.</summary>
	[Property, Group( "Spin" )] public float CapturedSpinDegreesPerSecond { get; set; } = 0.5f;

	/// <summary>Roughly how many seconds the spin takes to slow down at capture.</summary>
	[Property, Group( "Spin" )] public float SpinSlowSeconds { get; set; } = 4f;

	// ---- Earth --------------------------------------------------------------------------------

	/// <summary>Distance from the cavern's centre to Earth. Keep it inside the camera's far plane.</summary>
	[Property, Group( "Earth" )] public float EarthDistance { get; set; } = 9000f;

	/// <summary>Width of the Earth disc, in inches. At the default distance this fills much of the sky.</summary>
	[Property, Group( "Earth" )] public float EarthSize { get; set; } = 11000f;

	[Property, Group( "Earth" )] public Color EarthColor { get; set; } = new Color( 1f, 1f, 1f );

	/// <summary>Direction to Earth, used only when the cave has no holes to look through.</summary>
	[Property, Group( "Earth" )] public Vector3 EarthDirection { get; set; } = new Vector3( 0.3f, 0.2f, 1f );

	/// <summary>True once the asteroid is in orbit: the spin has slowed and Earth is showing.</summary>
	public bool Captured { get; private set; }

	GameObject _earth;
	readonly List<SpotLight> _beams = new();
	Vector3 _sunStart;       // direction the sunlight travels before any spin
	float _spinAngle;
	float _spinSpeed;
	float _ownElapsed;       // used when the scene has no StoryDirector

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

		CreateEarth();

		// The sun circles across the spin axis and shines straight down through the ceiling holes
		// once per turn. Wind it back so that first happens FirstBeamSeconds into play: the
		// opening is pure darkness, then one thin beam arrives, sweeps the floor and leaves.
		var axis = Axis();
		var down = (Vector3.Down - axis * Vector3.Dot( Vector3.Down, axis )).Normal;
		_sunStart = Rotation.FromAxis( axis, -SpinDegreesPerSecond * FirstBeamSeconds ) * down;
		_spinSpeed = SpinDegreesPerSecond;

		// The story may already be past capture (a late-enabled sky): skip straight to orbit.
		var director = StoryDirector.Get( Scene );
		if ( director is not null && director.Stage >= StoryStage.Captured )
		{
			_spinSpeed = CapturedSpinDegreesPerSecond;
			ShowEarth();
		}
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;

		var director = StoryDirector.Get( Scene );
		_ownElapsed += Time.Delta;

		if ( !Captured && director is not null && director.Stage >= StoryStage.Captured ) ShowEarth();

		// Ease the spin toward whichever speed the story calls for.
		float targetSpeed = Captured ? CapturedSpinDegreesPerSecond : SpinDegreesPerSecond;
		float ease = MathF.Min( 1f, Time.Delta * 3f / MathF.Max( SpinSlowSeconds, 0.01f ) );
		_spinSpeed += (targetSpeed - _spinSpeed) * ease;
		_spinAngle = (_spinAngle + _spinSpeed * Time.Delta) % 360f;

		UpdateBeams( director );
	}

	protected override void OnDestroy()
	{
		foreach ( var beam in _beams )
			if ( beam.IsValid() ) beam.GameObject.Destroy();
		_beams.Clear();
		if ( _earth.IsValid() ) _earth.Destroy();
	}

	// ---- Sun ----------------------------------------------------------------------------------

	Vector3 Axis() => SpinAxis.Length < 0.001f ? Vector3.Up : SpinAxis.Normal;

	/// <summary>Beams that are shining into the cave right now: where each starts and which way it points.</summary>
	public IEnumerable<(Vector3 Origin, Vector3 Direction)> LitBeams
	{
		get
		{
			foreach ( var beam in _beams )
				if ( beam.IsValid() && beam.Active && beam.Intensity > 0.5f )
					yield return (beam.WorldPosition, beam.WorldRotation.Forward);
		}
	}

	/// <summary>Direction the sunlight is travelling right now.</summary>
	public Vector3 SunDirection => Rotation.FromAxis( Axis(), _spinAngle ) * _sunStart;

	// One spotlight per hole (new holes, like the envoy's breach, get one too). Each sits outside
	// the shell behind its hole and shines along the sun's direction; it is on only while the sun
	// is on that side of the asteroid.
	void UpdateBeams( StoryDirector director )
	{
		var cave = Scene.GetAllComponents<CaveGenerator>().FirstOrDefault();
		if ( !cave.IsValid() ) return;

		float elapsed = director is not null ? director.Elapsed : _ownElapsed;
		float ramp = RampSeconds <= 0f ? 1f : Math.Clamp( elapsed / RampSeconds, 0f, 1f );
		float brightness = StartBrightness + (PeakBrightness - StartBrightness) * ramp;

		// A beam only exists while the sun is nearly overhead, and only one hole carries it per
		// pass: a single thin shaft that comes almost straight down, sweeps a little and is gone
		// until the asteroid has turned right round again.
		var sun = SunDirection;
		float overhead = Vector3.Dot( sun, Vector3.Down );
		bool window = overhead > BeamWindow;

		var holes = cave.HolePositions.ToList();
		if ( window && !_windowOpen && holes.Count > 0 )
		{
			_activeHole = _passes == 0 ? FirstHole( holes ) : (_activeHole + 1) % holes.Count;
			_passes++;
		}
		_windowOpen = window;

		// Fade in and out across the window so the beam swells, passes and dies away.
		float pass = Math.Clamp( (overhead - BeamWindow) / MathF.Max( 1f - BeamWindow, 0.01f ) * 2.5f, 0f, 1f );

		for ( int index = 0; index < holes.Count; index++ )
		{
			if ( index >= _beams.Count ) _beams.Add( CreateBeam() );
			var beam = _beams[index];

			bool lit = window && index == _activeHole;
			beam.GameObject.Enabled = lit;
			if ( !lit ) continue;

			beam.WorldPosition = holes[index] - sun * BeamOffset;
			beam.WorldRotation = Rotation.LookAt( sun );
			beam.LightColor = SunColor;
			beam.Intensity = brightness * pass * pass;
			beam.ConeOuter = BeamAngle;
			beam.ConeInner = BeamAngle * 0.75f;
			beam.Radius = BeamReach;
			beam.FogStrength = FogStrength;
		}

		for ( int index = holes.Count; index < _beams.Count; index++ ) _beams[index].GameObject.Enabled = false;
	}

	bool _windowOpen;
	int _activeHole;
	int _passes;

	/// <summary>The first beam uses the hole above the order fragment, so it comes down right onto it.</summary>
	int FirstHole( List<Vector3> holes )
	{
		var fragment = Scene.GetAllComponents<OrderFragment>().FirstOrDefault();
		if ( !fragment.IsValid() ) return 0;

		int best = 0; float bestDistance = float.MaxValue;
		for ( int i = 0; i < holes.Count; i++ )
		{
			float d = (holes[i] - fragment.WorldPosition).WithZ( 0 ).Length;
			if ( d < bestDistance ) { bestDistance = d; best = i; }
		}
		return best;
	}

	SpotLight CreateBeam()
	{
		var go = new GameObject( GameObject, true, "Sun Beam" );
		go.Flags |= GameObjectFlags.NotSaved;
		var light = go.Components.Create<SpotLight>();
		light.Shadows = true;
		light.FogMode = Light.FogInfluence.Enabled;

		// Draw the shaft itself, starting just inside the hole.
		var shaft = go.Components.Create<LightShaft>();
		shaft.StartOffset = BeamOffset + 20f;
		return light;
	}

	// ---- Earth --------------------------------------------------------------------------------

	void CreateEarth()
	{
		_earth = new GameObject( GameObject, false, "Earth" );
		_earth.Flags |= GameObjectFlags.NotSaved;

		// A huge unlit disc that always faces the camera. It fills the sky behind the holes, so
		// after capture every hole shows a piece of it from anywhere on the cave floor.
		var renderer = _earth.Components.Create<SpriteRenderer>();
		renderer.Sprite = ResourceLibrary.Get<Sprite>( "materials/dust/earth.sprite" );
		renderer.Lighting = false;
		renderer.Shadows = false;
		renderer.FogStrength = 0f;
		renderer.Color = EarthColor;
	}

	// Puts Earth outside the first hole in the shell and switches it on. Done at capture rather
	// than at start, so the hole is looked up where the rock is now.
	/// <summary>How many chunks the jolt shakes down from the ceiling around the player.</summary>
	[Property, Group( "Jolt" )] public int JoltDebris { get; set; } = 12;

	[Property, Group( "Jolt" )] public string DebrisModel { get; set; } = "models/props/rock_scatter/rock_scatter_01.vmdl";
	[Property, Group( "Jolt" )] public string DebrisMaterial { get; set; } = "materials/cave/cave_rock.vmat";

	/// <summary>The yank of orbit capture: rock comes off the ceiling and the lizard loses its grip.</summary>
	void Jolt()
	{
		var player = Scene.GetAllComponents<ReptileController>().FirstOrDefault();
		var around = player.IsValid() ? player.WorldPosition : WorldPosition;
		player?.ShakeLoose( new Vector3( Game.Random.Float( -1f, 1f ), Game.Random.Float( -1f, 1f ), 0.2f ).Normal * 260f );

		for ( int i = 0; i < JoltDebris; i++ )
		{
			// Find the ceiling above a random spot near the player.
			var spot = around + new Vector3( Game.Random.Float( -700f, 700f ), Game.Random.Float( -700f, 700f ), 0f );
			var up = Scene.Trace.Ray( spot + Vector3.Up * 40f, spot + Vector3.Up * 1500f ).Run();
			if ( !up.Hit ) continue;

			RockDebris.Spawn( up.HitPosition + Vector3.Down * 25f, Vector3.Random * 60f, Game.Random.Float( 1.2f, 4f ), DebrisModel, DebrisMaterial );
		}
	}

	void ShowEarth()
	{
		Captured = true;
		Jolt();
		if ( !_earth.IsValid() ) return;

		var cave = Scene.GetAllComponents<CaveGenerator>().FirstOrDefault();
		var centre = cave.IsValid() ? cave.WorldPosition : WorldPosition;

		var direction = EarthDirection;
		if ( cave.IsValid() )
		{
			var holes = cave.HolePositions.ToList();
			if ( holes.Count > 0 ) direction = holes[0] - centre;
		}
		if ( direction.Length < 0.001f ) direction = Vector3.Up;

		_earth.WorldPosition = centre + direction.Normal * EarthDistance;
		_earth.Enabled = true;
		var disc = _earth.Components.Get<SpriteRenderer>( FindMode.EverythingInSelf );
		if ( disc.IsValid() ) disc.Size = new Vector2( EarthSize, EarthSize );
	}
}