using UnityEngine;
using UnityStandardAssets.ImageEffects;

namespace Thousandto.Launcher.ExternalLibs
{
    [ExecuteInEditMode]
    [RequireComponent(typeof(Camera))]
    [AddComponentMenu("Image Effects/DistortEffect/DistortEffect(Simple)")]
    public class DistortEffectSimple : PostEffectsBase
    {

        [Range(0.0f, 1.0f)]
        public float DistortTimeFactor = 0.15f;
        //扭曲的强度
        [Range(0.0f, 0.2f)]
        public float DistortStrength = 0.01f;
        //噪声图
        public Texture NoiseTexture = null;
        //降采样系数
        public int downSample = 2;

        private Camera mainCam = null;                
        private Material _Material = null;
        private Shader _Shader = null;

        public void OnRenderImage(RenderTexture source, RenderTexture destination)
        {
            if (_Material)
            {
                _Material.SetTexture("_NoiseTex", NoiseTexture);
                _Material.SetFloat("_DistortTimeFactor", DistortTimeFactor);
                _Material.SetFloat("_DistortStrength", DistortStrength);
                _Material.SetTexture("_MaskTex", Texture2D.whiteTexture);
                Graphics.Blit(source, destination, _Material);
            }
            else
            {
                Graphics.Blit(source, destination);
            }
        }

        public override bool CheckResources()
        {
            CheckSupport(false);

            _Shader = ShaderFactory.Find("Ares/DistortEffect/DistortEffect");
            _Material = CheckShaderAndCreateMaterial(_Shader, _Material);

            if (!isSupported)
                ReportAutoDisable();
            return isSupported;
        }
    }
}