using UnityEngine;
using System.Collections;

public class L09_DoF : MonoBehaviour 
{
	[SerializeField]
	private Shader DOFShader;

	[SerializeField]
	private Shader DownsampleShader;

	[SerializeField]
	private float focalDistance = 5;

	[SerializeField]
	private float focusRange = 1;

	Material m_DoFMaterial = null;
	protected Material DoFMaterial
	{
		get
		{
			if (m_DoFMaterial == null)
			{
				m_DoFMaterial = new Material(DOFShader);
				m_DoFMaterial.hideFlags = HideFlags.DontSave;
			}
			return m_DoFMaterial;
		}
	}

	Material m_DownsampleMaterial = null;
	protected Material DownsampleMaterial
	{
		get
		{
			if (m_DownsampleMaterial == null)
			{
				m_DownsampleMaterial = new Material(DownsampleShader);
				m_DownsampleMaterial.hideFlags = HideFlags.DontSave;
			}
			return m_DownsampleMaterial;
		}
	}

	protected void OnDisable()
	{
		if (m_DoFMaterial)
		{
			DestroyImmediate(m_DoFMaterial);
		}

		if (m_DownsampleMaterial)
		{
			DestroyImmediate(m_DownsampleMaterial);
		}
	}

	void OnRenderImage(RenderTexture src, RenderTexture dst)
	{
		int rtW = src.width / 8;
		int rtH = src.height / 8;
		RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0);

		DownsampleMaterial.SetTexture("_MainTex", src);
		Graphics.Blit(src, buffer, DownsampleMaterial);

		DoFMaterial.SetFloat("FocusRange", focusRange);
		DoFMaterial.SetFloat("FocalDistance", focalDistance);
		DoFMaterial.SetTexture("_DownsampledTex", buffer);
		DoFMaterial.SetTexture("_MainTex", src);
		Graphics.Blit(src, dst, DoFMaterial);
	}
}
