﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using System;

[Serializable, VolumeComponentMenu("Post-processing/Snapshot Pro (HDRP)/Barrel Distortion")]
public sealed class BarrelDistortion : CustomPostProcessVolumeComponent, IPostProcessComponent
{
    [Tooltip("Color of the background around the 'screen'.")]
    public ColorParameter backgroundColor = new ColorParameter(Color.black);

    [Tooltip("Strength of the distortion. Values above zero cause CRT screen-like distortion; values below zero bulge outwards.")]
    public FloatParameter strength = new FloatParameter(0.0f);

    Material m_Material;

    public bool IsActive() => m_Material != null && strength.value != 0.0f;

    // Remember to add this post process in the Custom Post Process Orders list 
    // (Project Settings > HDRP Default Settings).
    public override CustomPostProcessInjectionPoint injectionPoint =>
        CustomPostProcessInjectionPoint.AfterPostProcess;

    const string kShaderName = "SnapshotProHDRP/BarrelDistortion";

    public override void Setup()
    {
        if (Shader.Find(kShaderName) != null)
        {
            m_Material = new Material(Shader.Find(kShaderName));
        }
        else
        {
            Debug.LogError($"Unable to find shader '{kShaderName}' for the Barrel Distortion effect.");
        }
    }

    public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
    {
        if (m_Material == null)
        {
            return;
        }

        m_Material.SetColor("_BackgroundColor", backgroundColor.value);
        m_Material.SetFloat("_Strength", strength.value);
        m_Material.SetTexture("_InputTexture", source);
        HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

    public override void Cleanup()
    {
        CoreUtils.Destroy(m_Material);
    }
}
