Sump/Presentation/SumpLighting.cs
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// The mood of each part of the Sump, laid over the lights the other modules build, never in
/// place of them. <see cref="SumpPresentation"/> adds it at runtime. Play mode only.
///
///   - Hub: a soft key and fill that travel with the player, so they are never lost in black.
///     Very dim, coloured by the Sump's seed. The cavern's own ambient light and fog (the
///     "Sump Air" object the cavern builds) are warmed and lifted a little for every healed misfit.
///   - Flashbacks: a grade per genre on top of what the memory builds: its fog is tinted (the fog
///     is only set when the arena is built, so tinting it fights nobody), and one soft light
///     travels with the player (cold moonlight on the farm, hard white in the lab that turns red
///     and throbs with the alarm, hot pink-amber in the studio).
///   - Finale: a deep red light on the player that beats with the planet's heart.
///   - Camera: film grain, chromatic aberration and sharpening per mode. Bloom, Vignette and
///     ColorAdjustments are left alone on purpose: the trauma module drives those for the fears.
///
/// About the fears. Every light made here hangs under the player's own object, and the player's
/// fear of light skips lights under the player; they also carry the misfits' glow tag, so a
/// light-shy misfit does not run from the player's own fill. None of them is bright, so nothing
/// here is tagged "sump_bright" (PlayerPhobia.BrightTag). If a bright light is ever added here
/// that should hurt a light-phobic player, give it its own object outside the player and that tag.
///
/// The lab's alarm is not published by the lab, so it is read from the outside: the orderly's
/// "Code grey" and the intercom's "Lockdown" raise it, and the power cut is seen as the arena's
/// ambient light going red. <see cref="LabAlarm"/> can be set directly if the lab ever wants to.
/// </summary>
[Title( "Sump Lighting" ), Category( "Sump" ), Icon( "wb_twilight" )]
public sealed class SumpLighting : Component
{
	// ---- The light that travels with the player ----------------------------------------------------
	/// <summary>Brightness of the hub's key light on the player. Keep it low: it is there to find your feet by.</summary>
	[Property, Group( "Follow" ), Range( 0f, 2f )] public float KeyBrightness { get; set; } = 0.22f;
	[Property, Group( "Follow" )] public float KeyRadius { get; set; } = 620f;
	/// <summary>Where the key hangs, relative to the player (forward, left, up).</summary>
	[Property, Group( "Follow" )] public Vector3 KeyOffset { get; set; } = new( -30f, 40f, 130f );
	/// <summary>Brightness of the fill, which is the key's opposite colour, low and from the other side.</summary>
	[Property, Group( "Follow" ), Range( 0f, 2f )] public float FillBrightness { get; set; } = 0.1f;
	[Property, Group( "Follow" )] public float FillRadius { get; set; } = 420f;
	[Property, Group( "Follow" )] public Vector3 FillOffset { get; set; } = new( 50f, -60f, 30f );
	/// <summary>How strongly the Sump's seed colours the key (0 white, 1 fully coloured).</summary>
	[Property, Group( "Follow" ), Range( 0f, 1f )] public float SeedTint { get; set; } = 0.45f;
	/// <summary>The follow light during the arrival's fall, as a fraction of the hub's.</summary>
	[Property, Group( "Follow" ), Range( 0f, 1f )] public float ArrivalLevel { get; set; } = 0.5f;
	/// <summary>Seconds the lights take to change when the mode does.</summary>
	[Property, Group( "Follow" )] public float BlendSeconds { get; set; } = 1.5f;

	// ---- The hub warming up ------------------------------------------------------------------------
	/// <summary>Ambient light gained per healed misfit, as a fraction of the cavern's own.</summary>
	[Property, Group( "Hub" ), Range( 0f, 1f )] public float BrightenPerHealed { get; set; } = 0.12f;
	/// <summary>Warm light added to the ambient per healed misfit.</summary>
	[Property, Group( "Hub" )] public Color WarmPerHealed { get; set; } = new( 0.012f, 0.007f, 0.002f );
	/// <summary>How far the fog is pulled toward the warm colour per healed misfit.</summary>
	[Property, Group( "Hub" ), Range( 0f, 0.2f )] public float FogWarmPerHealed { get; set; } = 0.04f;
	[Property, Group( "Hub" )] public Color FogWarm { get; set; } = new( 0.05f, 0.035f, 0.02f );
	/// <summary>The follow light also warms and brightens by this much per healed misfit.</summary>
	[Property, Group( "Hub" ), Range( 0f, 0.5f )] public float KeyPerHealed { get; set; } = 0.06f;
	/// <summary>Name of the object the cavern keeps its ambient light and fog on.</summary>
	[Property, Group( "Hub" )] public string CavernAirName { get; set; } = "Sump Air";

	// ---- Flashback grades --------------------------------------------------------------------------
	[Property, Group( "Flashbacks" )] public Color FarmNightLight { get; set; } = new( 0.35f, 0.5f, 0.9f );
	[Property, Group( "Flashbacks" )] public Color FarmDayLight { get; set; } = new( 1f, 0.8f, 0.5f );
	[Property, Group( "Flashbacks" )] public Color LabLight { get; set; } = new( 0.85f, 0.95f, 1f );
	[Property, Group( "Flashbacks" )] public Color LabAlarmLight { get; set; } = new( 1f, 0.08f, 0.05f );
	[Property, Group( "Flashbacks" )] public Color StudioLight { get; set; } = new( 1f, 0.45f, 0.55f );
	/// <summary>Brightness of the genre's light on the player.</summary>
	[Property, Group( "Flashbacks" ), Range( 0f, 2f )] public float GradeBrightness { get; set; } = 0.3f;
	[Property, Group( "Flashbacks" )] public float GradeRadius { get; set; } = 700f;
	/// <summary>What the memory's fog colour is multiplied by, per genre.</summary>
	[Property, Group( "Flashbacks" )] public Color FarmNightFog { get; set; } = new( 0.7f, 0.85f, 1.25f );
	[Property, Group( "Flashbacks" )] public Color FarmDayFog { get; set; } = new( 1.05f, 0.98f, 0.9f );
	[Property, Group( "Flashbacks" )] public Color LabFog { get; set; } = new( 0.95f, 1.02f, 1.08f );
	[Property, Group( "Flashbacks" )] public Color StudioFog { get; set; } = new( 1.6f, 0.9f, 1.2f );
	/// <summary>What the lab's fog turns to at full alarm (a colour, not a multiplier).</summary>
	[Property, Group( "Flashbacks" )] public Color LabAlarmFog { get; set; } = new( 0.22f, 0.02f, 0.02f );
	/// <summary>Throbs per second of the lab's alarm light.</summary>
	[Property, Group( "Flashbacks" )] public float AlarmThrob { get; set; } = 1.6f;

	// ---- Finale ------------------------------------------------------------------------------------
	[Property, Group( "Finale" )] public Color HeartLight { get; set; } = new( 1f, 0.22f, 0.12f );
	/// <summary>Brightness of the heart's light between beats and on the beat.</summary>
	[Property, Group( "Finale" )] public Vector2 HeartBrightness { get; set; } = new( 0.12f, 0.6f );
	[Property, Group( "Finale" )] public float HeartRadius { get; set; } = 900f;

	// ---- Camera ------------------------------------------------------------------------------------
	[Property, Group( "Camera" )] public bool UsePostProcess { get; set; } = true;
	/// <summary>Film grain per mode: arrival, hub, flashback, finale. Never more than <see cref="MaxGrain"/> in total.</summary>
	[Property, Group( "Camera" )] public float GrainArrival { get; set; } = 0.015f;
	[Property, Group( "Camera" )] public float GrainHub { get; set; } = 0.01f;
	[Property, Group( "Camera" )] public float GrainFlashback { get; set; } = 0.02f;
	[Property, Group( "Camera" )] public float GrainFinale { get; set; } = 0.015f;
	/// <summary>Colour fringing at the edges of a memory, and extra at full lab alarm.</summary>
	[Property, Group( "Camera" )] public float FringeFlashback { get; set; } = 0.25f;
	[Property, Group( "Camera" )] public float FringeAlarm { get; set; } = 0.5f;
	/// <summary>Colour fringing in the finale between beats and on the beat.</summary>
	[Property, Group( "Camera" )] public Vector2 FringeFinale { get; set; } = new( 0.1f, 0.7f );
	/// <summary>Sharpening in the lab (harsh) and in the studio (video).</summary>
	[Property, Group( "Camera" )] public float SharpenLab { get; set; } = 0.5f;
	[Property, Group( "Camera" )] public float SharpenStudio { get; set; } = 0.3f;

	/// <summary>
	/// The most film grain ever put on the camera, whatever the properties above (or a grain the
	/// camera already had) add up to. Above about this the grain lifts the blacks to grey, and
	/// the Sump is mostly blacks.
	/// </summary>
	public const float MaxGrain = 0.02f;

	/// <summary>The hub's ambient light is kept between these (its brightest channel): readable, but still a cave.</summary>
	public const float AmbientFloor = 0.13f, AmbientCeiling = 0.3f;

	/// <summary>The lab's alarm, 0 quiet to 3 power failure. Guessed from the outside; settable.</summary>
	public static int LabAlarm { get; set; }

	GameObject _rig;
	PointLight _key, _fill, _grade;
	float _keyLevel, _gradeLevel, _heartLevel, _alarmLevel;
	Color _gradeColor = Color.White;
	float _healedSmooth;

	AmbientLight _cavernAmbient;
	Color _cavernAmbientWas;
	Fog _cavernFog, _arenaFog;   // made by SumpFog for the cavern and the arenas; this only tints theirs
	Color _cavernFogWas, _arenaFogWas;
	AmbientLight _arenaAmbient;
	TimeSince _sinceLooked = 10f;

	FilmGrain _grain;
	ChromaticAberration _fringe;
	Sharpen _sharpen;
	float _grainWas, _fringeWas, _sharpenWas;
	bool _grainMine, _fringeMine, _sharpenMine, _postTried;
	float _grainNow, _fringeNow, _sharpenNow;

	bool _listening;
	SumpMode _lastMode;

	protected override void OnEnabled()
	{
		if ( Scene.IsEditor ) return;
		Sump.Said += OnSaid;
		_listening = true;
		LabAlarm = 0;
		_healedSmooth = SumpState.HealedCount;
	}

	protected override void OnDisabled()
	{
		if ( _listening ) { Sump.Said -= OnSaid; _listening = false; }
		RestoreCavern();
		RestoreArenaFog();
		RestorePost();
		if ( _rig.IsValid() ) _rig.Destroy();
		_rig = null;
		_key = _fill = _grade = null;
	}

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

		var mode = Sump.Mode;
		if ( mode != _lastMode )
		{
			if ( mode != SumpMode.Flashback ) { LabAlarm = 0; RestoreArenaFog(); }
			_lastMode = mode;
		}

		var profile = mode == SumpMode.Flashback
			? (FlashbackRunner.Current.IsValid() ? FlashbackRunner.Current.Profile : null) ?? Sump.ActiveFlashback
			: null;

		float dt = Time.Delta;
		float blend = Math.Clamp( dt / MathF.Max( BlendSeconds, 0.05f ), 0f, 1f );
		_healedSmooth += (SumpState.HealedCount - _healedSmooth) * Math.Clamp( dt * 0.5f, 0f, 1f );

		if ( _sinceLooked > 1f )
		{
			_sinceLooked = 0f;
			FindAir( mode );
		}

		UpdateAlarm( mode, profile, dt );
		UpdateFollow( mode, profile, blend );
		UpdateCavern( mode );
		UpdateArenaFog( profile );
		UpdatePost( mode, profile, blend );
	}

	// ---- The lights on the player ------------------------------------------------------------------

	void EnsureRig()
	{
		if ( _rig.IsValid() || !Sump.Player.IsValid() ) return;

		// Under the player, so the player's own fear of light does not count these.
		_rig = new GameObject( Sump.Player.GameObject, true, "Sump Mood Lights" );
		_rig.Flags |= GameObjectFlags.NotSaved;
		_key = AddLight( "Key", KeyRadius );
		_fill = AddLight( "Fill", FillRadius );
		_grade = AddLight( "Grade", GradeRadius );
	}

	PointLight AddLight( string name, float radius )
	{
		var go = new GameObject( _rig, true, name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.Tags.Add( MisfitBody.GlowTag );   // light-shy misfits do not run from these
		var light = go.Components.Create<PointLight>();
		light.Radius = radius;
		light.Shadows = false;
		light.LightColor = Color.Black;
		light.Enabled = false;
		return light;
	}

	void UpdateFollow( SumpMode mode, MisfitProfile profile, float blend )
	{
		EnsureRig();
		if ( !_rig.IsValid() ) return;

		// The rig keeps the world's up, whatever the lizard's body is doing.
		_rig.WorldRotation = Rotation.FromYaw( Sump.Player.WorldRotation.Yaw() );
		_rig.WorldScale = Vector3.One;

		// Key and fill: the hub, dimmer in the arrival, off inside memories and in the finale.
		float keyTarget = mode == SumpMode.Hub ? 1f : mode == SumpMode.Arrival ? ArrivalLevel : mode == SumpMode.Ended ? 0.6f : 0f;
		if ( mode == SumpMode.Hub && !SumpCavern.HubVisible ) keyTarget = 0f;
		_keyLevel += (keyTarget - _keyLevel) * blend;

		var seedColor = SeedColor( 0f );
		var warm = new Color( 1f, 0.78f, 0.5f );
		float warmth = Math.Clamp( _healedSmooth * KeyPerHealed, 0f, 0.6f );
		var keyColor = Color.Lerp( Color.Lerp( Color.White, seedColor, SeedTint ), warm, warmth );
		var fillColor = Color.Lerp( Color.White, SeedColor( 180f ), SeedTint );
		SetLight( _key, KeyOffset, KeyRadius, keyColor, KeyBrightness * (1f + warmth) * _keyLevel );
		SetLight( _fill, FillOffset, FillRadius, fillColor, FillBrightness * _keyLevel );

		// The grade: one light for whichever memory this is, or the heart in the finale.
		Color gradeTarget = _gradeColor;
		float gradeLevel = 0f, brightness = GradeBrightness, radius = GradeRadius;
		if ( profile is not null )
		{
			gradeLevel = 1f;
			switch ( profile.Genre )
			{
				case FlashbackGenre.FarmHorror:
					gradeTarget = profile.Contact == FirstContact.AdoptedThenForgotten ? FarmDayLight : FarmNightLight;
					break;
				case FlashbackGenre.LabEscape:
					gradeTarget = Color.Lerp( LabLight, LabAlarmLight, _alarmLevel );
					// The alarm throbs: never fully out, so the player can still see the floor.
					brightness *= 1f + _alarmLevel * (0.6f * MathF.Sin( Time.Now * MathF.PI * 2f * AlarmThrob ) - 0.1f);
					break;
				default:
					gradeTarget = StudioLight;
					break;
			}
		}
		_gradeLevel += (gradeLevel - _gradeLevel) * blend;
		_gradeColor = Color.Lerp( _gradeColor, gradeTarget, Math.Clamp( blend * 2f, 0f, 1f ) );

		_heartLevel += ((mode == SumpMode.Finale ? 1f : 0f) - _heartLevel) * blend;
		if ( _heartLevel > 0.01f && _gradeLevel < 0.01f )
		{
			float pulse = SumpPresentation.HeartPulse;
			SetLight( _grade, new Vector3( 0f, 0f, 90f ), HeartRadius, HeartLight, (HeartBrightness.x + (HeartBrightness.y - HeartBrightness.x) * pulse) * _heartLevel );
		}
		else
		{
			SetLight( _grade, new Vector3( -20f, 0f, 150f ), radius, _gradeColor, MathF.Max( brightness, 0f ) * _gradeLevel );
		}
	}

	static void SetLight( PointLight light, Vector3 offset, float radius, Color color, float brightness )
	{
		if ( !light.IsValid() ) return;
		bool on = brightness > 0.004f;
		if ( light.Enabled != on ) light.Enabled = on;
		if ( !on ) return;
		light.GameObject.LocalPosition = offset;
		light.Radius = radius;
		light.LightColor = (color * brightness).WithAlpha( 1f );
	}

	/// <summary>The Sump's own colour: a hue from its seed, fully saturated. Mixed down by <see cref="SeedTint"/>.</summary>
	static Color SeedColor( float hueShift )
	{
		float hue = ((MisfitGenerator.Mix( SumpState.Seed, 0xC010, 7 ) & 0xFFFF) % 360 + hueShift) % 360f;
		return new ColorHsv( hue, 0.75f, 1f, 1f ).ToColor();
	}

	// ---- The hub's own air -------------------------------------------------------------------------

	/// <summary>Finds the cavern's ambient light and fog, and the current memory's fog. Looked for about once a second.</summary>
	void FindAir( SumpMode mode )
	{
		try
		{
			if ( !_cavernAmbient.IsValid() )
			{
				_cavernAmbient = Scene.GetAllComponents<AmbientLight>().FirstOrDefault( a => a.IsValid() && a.GameObject.Name == CavernAirName );
				if ( _cavernAmbient.IsValid() ) _cavernAmbientWas = _cavernAmbient.Color;
			}
			if ( !_cavernFog.IsValid() )
			{
				_cavernFog = Scene.GetAllComponents<Fog>().FirstOrDefault( f => f.IsValid() && f.GameObject.Name == CavernAirName );
				if ( _cavernFog.IsValid() ) _cavernFogWas = SumpFog.ColorOf( _cavernFog );
			}

			if ( mode == SumpMode.Flashback )
			{
				if ( !_arenaFog.IsValid() )
				{
					_arenaFog = Scene.GetAllComponents<Fog>().FirstOrDefault( f => f.IsValid() && f != _cavernFog && NearFlashback( f.WorldPosition ) );
					if ( _arenaFog.IsValid() ) _arenaFogWas = SumpFog.ColorOf( _arenaFog );
				}
				if ( !_arenaAmbient.IsValid() )
					_arenaAmbient = Scene.GetAllComponents<AmbientLight>().FirstOrDefault( a => a.IsValid() && a != _cavernAmbient && NearFlashback( a.WorldPosition ) );
			}
		}
		catch ( Exception ) { }
	}

	static bool NearFlashback( Vector3 position ) => position.Distance( Sump.FlashbackOrigin ) < 25000f;

	void UpdateCavern( SumpMode mode )
	{
		if ( mode != SumpMode.Hub && mode != SumpMode.Arrival ) return;
		float healed = _healedSmooth;

		if ( _cavernAmbient.IsValid() )
		{
			var c = _cavernAmbientWas * (1f + BrightenPerHealed * healed) + WarmPerHealed * healed;

			// Held between two levels whatever the cavern was given and however many are healed:
			// never so low the floor is lost, never so high the dark stops being dark.
			float peak = MathF.Max( c.r, MathF.Max( c.g, c.b ) );
			if ( peak < 0.0001f ) c = new Color( AmbientFloor, AmbientFloor, AmbientFloor );
			else if ( peak < AmbientFloor ) c *= AmbientFloor / peak;
			else if ( peak > AmbientCeiling ) c *= AmbientCeiling / peak;
			_cavernAmbient.Color = c.WithAlpha( _cavernAmbientWas.a );
		}
		if ( _cavernFog.IsValid() )
			SumpFog.Tint( _cavernFog, Color.Lerp( _cavernFogWas, FogWarm, Math.Clamp( FogWarmPerHealed * healed, 0f, 0.6f ) ).WithAlpha( _cavernFogWas.a ) );
	}

	void RestoreCavern()
	{
		if ( _cavernAmbient.IsValid() ) _cavernAmbient.Color = _cavernAmbientWas;
		SumpFog.Tint( _cavernFog, _cavernFogWas );
		_cavernAmbient = null;
		_cavernFog = null;
	}

	// ---- Memories ----------------------------------------------------------------------------------

	void UpdateArenaFog( MisfitProfile profile )
	{
		if ( profile is null || !_arenaFog.IsValid() ) return;

		Color tint = profile.Genre switch
		{
			FlashbackGenre.FarmHorror => profile.Contact == FirstContact.AdoptedThenForgotten ? FarmDayFog : FarmNightFog,
			FlashbackGenre.LabEscape => LabFog,
			_ => StudioFog,
		};
		var graded = new Color( _arenaFogWas.r * tint.r, _arenaFogWas.g * tint.g, _arenaFogWas.b * tint.b, _arenaFogWas.a );
		if ( profile.Genre == FlashbackGenre.LabEscape ) graded = Color.Lerp( graded, LabAlarmFog.WithAlpha( _arenaFogWas.a ), _alarmLevel );
		SumpFog.Tint( _arenaFog, graded );
	}

	void RestoreArenaFog()
	{
		SumpFog.Tint( _arenaFog, _arenaFogWas );
		_arenaFog = null;
		_arenaAmbient = null;
	}

	void OnSaid( string speaker, string text )
	{
		if ( Sump.Mode != SumpMode.Flashback || string.IsNullOrEmpty( text ) ) return;
		if ( text.Contains( "Code grey", StringComparison.OrdinalIgnoreCase ) ) LabAlarm = Math.Max( LabAlarm, 1 );
		else if ( text.StartsWith( "Lockdown", StringComparison.OrdinalIgnoreCase ) ) LabAlarm = Math.Max( LabAlarm, 2 );
	}

	void UpdateAlarm( SumpMode mode, MisfitProfile profile, float dt )
	{
		bool lab = profile is not null && profile.Genre == FlashbackGenre.LabEscape;
		if ( !lab ) { LabAlarm = 0; _alarmLevel = 0f; return; }

		// A rewind puts the memory back to before the alarm; the power cut shows as red ambient light.
		if ( Sump.CardTitle == "THE MEMORY REWINDS" ) LabAlarm = 0;
		if ( _arenaAmbient.IsValid() )
		{
			var a = _arenaAmbient.Color;
			if ( a.r > 0.05f && a.r > a.g * 3f && a.r > a.b * 3f ) LabAlarm = 3;
		}

		float target = Math.Clamp( LabAlarm / 3f, 0f, 1f );
		_alarmLevel += (target - _alarmLevel) * Math.Clamp( dt * 2f, 0f, 1f );
	}

	// ---- Camera ------------------------------------------------------------------------------------

	void UpdatePost( SumpMode mode, MisfitProfile profile, float blend )
	{
		if ( !UsePostProcess ) return;

		float grain = mode switch
		{
			SumpMode.Arrival => GrainArrival,
			SumpMode.Hub => GrainHub,
			SumpMode.Flashback => GrainFlashback,
			SumpMode.Finale => GrainFinale,
			_ => GrainHub,
		};
		float fringe = 0f, sharpen = 0f;
		if ( profile is not null )
		{
			fringe = FringeFlashback + FringeAlarm * _alarmLevel;
			sharpen = profile.Genre == FlashbackGenre.LabEscape ? SharpenLab : profile.Genre == FlashbackGenre.TalkShow ? SharpenStudio : 0f;
		}
		else if ( mode == SumpMode.Finale )
		{
			fringe = FringeFinale.x + (FringeFinale.y - FringeFinale.x) * SumpPresentation.HeartPulse;
		}

		_grainNow += (grain - _grainNow) * blend;
		_sharpenNow += (sharpen - _sharpenNow) * blend;
		// The heart's beat should land on the beat, so the fringe follows faster.
		_fringeNow += (fringe - _fringeNow) * Math.Clamp( blend * 8f, 0f, 1f );

		try
		{
			if ( !_postTried )
			{
				if ( !Scene.Camera.IsValid() ) return;
				_postTried = true;
				FindPost();
			}

			if ( _grain.IsValid() )
			{
				float total = _grainWas + _grainNow;
				_grain.Intensity = float.IsNaN( total ) ? 0f : Math.Clamp( total, 0f, MaxGrain );
				if ( _grainMine ) _grain.Enabled = _grainNow > 0.005f;
			}
			if ( _fringe.IsValid() )
			{
				_fringe.Scale = _fringeWas + _fringeNow;
				if ( _fringeMine ) _fringe.Enabled = _fringeNow > 0.005f;
			}
			if ( _sharpen.IsValid() )
			{
				_sharpen.Scale = _sharpenWas + _sharpenNow;
				if ( _sharpenMine ) _sharpen.Enabled = _sharpenNow > 0.005f;
			}
		}
		catch ( Exception e )
		{
			UsePostProcess = false;
			Log.Warning( $"SumpLighting: post-processing switched off: {e.Message}" );
		}
	}

	/// <summary>Borrows the camera's grain, fringe and sharpen, or adds them. Each is separate: a missing one costs only its own effect.</summary>
	void FindPost()
	{
		var camera = Scene.Camera;
		if ( !camera.IsValid() ) return;

		try
		{
			_grain = camera.Components.Get<FilmGrain>();
			_grainMine = !_grain.IsValid();
			if ( _grainMine )
			{
				_grain = camera.Components.Create<FilmGrain>();
				_grain.Intensity = 0f;
				_grain.Enabled = false;
			}
			_grainWas = _grainMine ? 0f : _grain.Intensity;
		}
		catch ( Exception e ) { _grain = null; Log.Warning( $"SumpLighting: no film grain: {e.Message}" ); }

		try
		{
			_fringe = camera.Components.Get<ChromaticAberration>();
			_fringeMine = !_fringe.IsValid();
			if ( _fringeMine )
			{
				_fringe = camera.Components.Create<ChromaticAberration>();
				_fringe.Scale = 0f;
				_fringe.Enabled = false;
			}
			_fringeWas = _fringeMine ? 0f : _fringe.Scale;
		}
		catch ( Exception e ) { _fringe = null; Log.Warning( $"SumpLighting: no chromatic aberration: {e.Message}" ); }

		try
		{
			_sharpen = camera.Components.Get<Sharpen>();
			_sharpenMine = !_sharpen.IsValid();
			if ( _sharpenMine )
			{
				_sharpen = camera.Components.Create<Sharpen>();
				_sharpen.Scale = 0f;
				_sharpen.Enabled = false;
			}
			_sharpenWas = _sharpenMine ? 0f : _sharpen.Scale;
		}
		catch ( Exception e ) { _sharpen = null; Log.Warning( $"SumpLighting: no sharpen: {e.Message}" ); }
	}

	void RestorePost()
	{
		try
		{
			if ( _grain.IsValid() ) { if ( _grainMine ) _grain.Destroy(); else _grain.Intensity = _grainWas; }
			if ( _fringe.IsValid() ) { if ( _fringeMine ) _fringe.Destroy(); else _fringe.Scale = _fringeWas; }
			if ( _sharpen.IsValid() ) { if ( _sharpenMine ) _sharpen.Destroy(); else _sharpen.Scale = _sharpenWas; }
		}
		catch ( Exception ) { }
		_grain = null;
		_fringe = null;
		_sharpen = null;
		_postTried = false;
	}
}