using UnityEngine;

public class FlipnotePostProcessing : MonoBehaviour
{
    public Material saturateMaterial;
    public Material ditheringMaterial;
    public Material depthNormalsMaterial;
    public Material edgeDetectionMaterial;
    public Material compositeMaterial;

    private Camera cam;

    private RenderTexture saturateTexture;
    private RenderTexture ditheringTexture;
    private RenderTexture depthNormalsTexture;
    private RenderTexture edgeDetectionTexture;

    void Start()
    {
        cam = this.GetComponent<Camera>();
        cam.depthTextureMode = cam.depthTextureMode | DepthTextureMode.DepthNormals;

        saturateTexture = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
        ditheringTexture = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
        depthNormalsTexture = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
        edgeDetectionTexture = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 24);
    }

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        // Run the dithering shader on the source image
        Graphics.Blit(source, saturateTexture, saturateMaterial);

        // Run the dithering shader on the saturate image
        Graphics.Blit(saturateTexture, ditheringTexture, ditheringMaterial);

        // Run the depth-normals shader on the source image
        Graphics.Blit(source, depthNormalsTexture, depthNormalsMaterial);

        // Get the viewspace to worldspace matrix and pass it to edge detection shader
        Matrix4x4 viewToWorld = cam.cameraToWorldMatrix;
        edgeDetectionMaterial.SetMatrix("_viewToWorld", viewToWorld);

        // Pass the depth-normals texture and the original texture to the edge detection shader
        edgeDetectionMaterial.SetTexture("_MainTex", depthNormalsTexture);
        edgeDetectionMaterial.SetTexture("_OriginalTex", source);

        // Run edge detection on the depth-normal map
        Graphics.Blit(depthNormalsTexture, edgeDetectionTexture, edgeDetectionMaterial);

        // Pass the dithered texture and the edges to the final composite shader
        compositeMaterial.SetTexture("_DitherTex", ditheringTexture);
        compositeMaterial.SetTexture("_EdgeTex", edgeDetectionTexture);

        // Render the final image
        Graphics.Blit(edgeDetectionTexture, destination, compositeMaterial);
    }
}
