﻿using UnityEngine;
using UnityEngine.Rendering;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

//attach this script to your camera object
public class CreateStereoCubemaps : MonoBehaviour
{
    
    public RenderTexture cubemapLeft;
    public RenderTexture cubemapRight;
    public RenderTexture equirect;
    public bool renderStereo = false;
    public float stereoSeparation = 1f;
    public int ImageNumber = 100000;

    private void Start()
    {
        Time.captureFramerate = 25;
    }

    void Update()
    {
        Camera cam = GetComponent<Camera>();

        if (cam == null)
        {
            cam = GetComponentInParent<Camera>();
        }

        if (cam == null)
        {
            Debug.Log("stereo 360 capture node has no camera or parent camera");
        }

        if (renderStereo)
        {
            cam.stereoSeparation = stereoSeparation;
            cam.RenderToCubemap(cubemapLeft, 63, Camera.MonoOrStereoscopicEye.Left);
            cam.RenderToCubemap(cubemapRight, 63, Camera.MonoOrStereoscopicEye.Right);
            
        }
        else
        {
            cam.RenderToCubemap(cubemapLeft, 63, Camera.MonoOrStereoscopicEye.Mono);
        }

        

        if (equirect == null)
        {
            return;
        }
        
        if (renderStereo)
        {
            cubemapLeft.ConvertToEquirect(equirect, Camera.MonoOrStereoscopicEye.Left);
            cubemapRight.ConvertToEquirect(equirect, Camera.MonoOrStereoscopicEye.Right);
           
            
        }
        else
        {
            
            cubemapLeft.ConvertToEquirect(equirect, Camera.MonoOrStereoscopicEye.Mono);
            // location where the images will be saved. If you are adding a subfolder to this address, remeber to indiate that using double \ as \\
            DumpRenderTexture(equirect, "C:\\Users\\GEOG497\\Desktop\\Images", ImageNumber);
            ImageNumber += 1;
        }
    }

    public static void DumpRenderTexture(RenderTexture rt, string pngOutPath, int number)
    {
        var oldRT = RenderTexture.active;

        var tex = new Texture2D(rt.width, rt.height);
        RenderTexture.active = rt;
        tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
        tex.Apply();

        
        File.WriteAllBytes(pngOutPath + "/Image_" + number.ToString("D6") + ".png" , tex.EncodeToPNG());
        RenderTexture.active = oldRT;
        
    }
}