Skip to content

Instantly share code, notes, and snippets.

@SamyBencherif
Last active February 7, 2022 02:34
Show Gist options
  • Save SamyBencherif/9f342f2032b247b967a1ada9605ecf64 to your computer and use it in GitHub Desktop.
Save SamyBencherif/9f342f2032b247b967a1ada9605ecf64 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
public class RaymarchCamera : MonoBehaviour
{
[SerializeField]
public Shader _shader;
public Material _raymarchMat;
public Camera _cam;
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (!_raymarchMat && _shader)
{
_raymarchMat = new Material(_shader);
_raymarchMat.hideFlags = HideFlags.HideAndDontSave;
}
if (!_cam)
{
_cam = GetComponent<Camera>();
}
if (!_raymarchMat)
{
Graphics.Blit(source, destination);
return;
}
_raymarchMat.SetMatrix("_CamFrustum", CamFrustum(_cam));
_raymarchMat.SetMatrix("_CamToWorld", _cam.cameraToWorldMatrix);
_raymarchMat.SetVector("_CamWorldSpace", _cam.transform.position);
RenderTexture.active = destination;
GL.PushMatrix();
GL.LoadOrtho();
_raymarchMat.SetPass(0);
GL.Begin(GL.QUADS);
// BL
GL.MultiTexCoord2(0, 0.0f, 0.0f);
GL.Vertex3(0.0f, 0.0f, 3.0f);
// BR
GL.MultiTexCoord2(0, 1.0f, 0.0f);
GL.Vertex3(1.0f, 0.0f, 2.0f);
// TR
GL.MultiTexCoord2(0, 1.0f, 1.0f);
GL.Vertex3(1.0f, 1.0f, 1.0f);
// TL
GL.MultiTexCoord2(0, 0.0f, 1.0f);
GL.Vertex3(0.0f, 1.0f, 0.0f);
GL.End();
GL.PopMatrix();
}
private Matrix4x4 CamFrustum(Camera cam)
{
Matrix4x4 frustum = Matrix4x4.identity;
float fov = Mathf.Tan((cam.fieldOfView * 0.5f) * Mathf.Deg2Rad);
Vector3 goUp = Vector3.up * fov;
Vector3 goRight = Vector3.right * fov * cam.aspect;
Vector3 TL = (-Vector3.forward - goRight + goUp);
Vector3 TR = (-Vector3.forward + goRight + goUp);
Vector3 BR = (-Vector3.forward + goRight - goUp);
Vector3 BL = (-Vector3.forward - goRight - goUp);
frustum.SetRow(0, TL);
frustum.SetRow(1, TR);
frustum.SetRow(2, BR);
frustum.SetRow(3, BL);
return frustum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment