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

[Serializable, VolumeComponentMenu("Post-processing/Snapshot Pro (HDRP)/Scanlines")]
public sealed class Scanlines : CustomPostProcessVolumeComponent, IPostProcessComponent
{
    [Tooltip("Scanlines Texture.")]
    public TextureParameter scanlineTex = new TextureParameter(null);

    [Tooltip("Strength of the effect.")]
    public ClampedFloatParameter strength = new ClampedFloatParameter(0.0f, 0.0f, 1.0f);

    [Tooltip("Pixel size of the scanlines.")]
    public ClampedIntParameter size = new ClampedIntParameter(8, 1, 64);

    Material m_Material;

    public bool IsActive() => m_Material != null && scanlineTex.value != 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/Scanlines";

    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 Scanlines effect.");
        }  
    }

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

        m_Material.SetTexture("_ScanlineTex", scanlineTex.value);
        m_Material.SetFloat("_Strength", strength.value);
        m_Material.SetInt("_Size", size.value);

        m_Material.SetTexture("_InputTexture", source);
        HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

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