using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if ZED_HDRP || ZED_URP
using UnityEngine.Rendering;
#endif
///
/// Copies an attached camera's output to a target RenderTexture each frame.
/// Also includes an option to pause this.
/// The pause feature is not used in the MR calibration scene.
[RequireComponent(typeof(Camera))]
public class DrawOutputToPlane : MonoBehaviour
{
///
/// Intermediary texture we copy to when unpaused, which we also set as the target Renderer's main texture.
///
private RenderTexture targetTexture;
///
/// Texture applied to the final material.
///
private RenderTexture outputTexture;
///
/// Renderer onto whose material this class will copy the camera's output.
///
public MeshRenderer outputRenderer;
///
/// Set to true to pause the updates, leaving the texture to show the last rendered frame until unpaused.
///
public static bool pauseTextureUpdate = false;
private void Awake()
{
Camera cam = GetComponent();
targetTexture = new RenderTexture(cam.pixelWidth, cam.pixelHeight, 0);
targetTexture.Create();
outputTexture = new RenderTexture(targetTexture);
outputTexture.Create();
cam.targetTexture = targetTexture;
if (outputRenderer) outputRenderer.material.SetTexture("_MainTex", outputTexture); //TODO: Cache shader ID.
// (targetRenderer) targetRenderer.material.mainTexture = targetTexture;
#if ZED_HDRP || ZED_URP
RenderPipelineManager.endFrameRendering += OnFrameEnd;
if (outputRenderer) outputRenderer.material.mainTexture = targetTexture;
#endif
}
#if ZED_HDRP || ZED_URP
///
/// Blits the intermediary targetTexture to the final outputTexture for rendering. Used in SRP because there is no OnRenderImage automatic function.
///
private void OnFrameEnd(ScriptableRenderContext context, Camera[] cams)
{
if (targetTexture != null && pauseTextureUpdate != true)
{
Graphics.Blit(targetTexture, outputTexture);
}
}
#endif
///
/// Copies the output to the intermediary texture whenever the attached camera renders.
///
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (targetTexture != null && pauseTextureUpdate != true)
{
Graphics.Blit(source, outputTexture);
}
}
}