using UnityEngine;
using UnityEngine.Rendering;

/// <summary>Reproduces the supplied hemisphere lighting after reopening a scene.</summary>
[ExecuteAlways]
public sealed class EnvironmentAmbient : MonoBehaviour
{
    [SerializeField] Color sky, horizon, ground;
    SphericalHarmonicsL2 probe;

    public void Configure(Color skyColor,Color horizonColor,Color groundColor)
    {
        sky=skyColor;horizon=horizonColor;ground=groundColor;
        Rebuild();
    }

    void OnEnable()
    {
        Rebuild();
        RenderPipelineManager.beginCameraRendering+=BeforeCamera;
    }
    void OnDisable()=>RenderPipelineManager.beginCameraRendering-=BeforeCamera;
    void OnValidate()=>Rebuild();
    void LateUpdate()=>RenderSettings.ambientProbe=probe;
    void BeforeCamera(ScriptableRenderContext context,Camera camera)=>RenderSettings.ambientProbe=probe;

    void Rebuild()
    {
        RenderSettings.ambientMode=AmbientMode.Trilight;
        RenderSettings.ambientSkyColor=sky;RenderSettings.ambientEquatorColor=horizon;RenderSettings.ambientGroundColor=ground;
        probe=new SphericalHarmonicsL2();
        probe.AddAmbientLight(horizon.linear*.7f);
        probe.AddDirectionalLight(Vector3.up,sky.linear,1.15f);
        probe.AddDirectionalLight(Vector3.down,ground.linear,.7f);
        RenderSettings.ambientProbe=probe;
    }
}
