Skip to content

Instantly share code, notes, and snippets.

@hvent90
Created January 21, 2019 04:33
Show Gist options
  • Save hvent90/98b6d70de04ec370bb9869ca3fa69e39 to your computer and use it in GitHub Desktop.
Save hvent90/98b6d70de04ec370bb9869ca3fa69e39 to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
[Serializable]
public sealed class ShaderParameter : ParameterOverride<Shader> { }
[Serializable]
[PostProcess(typeof(RaymarchPostProcessRenderer), PostProcessEvent.AfterStack, "Raymarch/RaymarchHDRP")]
public sealed class RaymarchPostProcess : PostProcessEffectSettings
{
public ShaderParameter _shader = new ShaderParameter { value = null };
}
public sealed class RaymarchPostProcessRenderer : PostProcessEffectRenderer<RaymarchPostProcess>
{
[SerializeField]
private Shader _shader;
public Material _raymarchMaterial
{
get
{
if (!_raymarchMat && _shader)
{
_raymarchMat = new Material(_shader);
_raymarchMat.hideFlags = HideFlags.HideAndDontSave;
}
return _raymarchMat;
}
}
private Material _raymarchMat;
public Camera _camera
{
get
{
if (!_cam)
{
_cam = Camera.main;
}
return _cam;
}
}
private Camera _cam;
public override void Render(PostProcessRenderContext context)
{
if (!_shader)
_shader = settings._shader.value;
if (!_cam)
_cam = Camera.main;
PropertySheet sheet = context.propertySheets.Get(Shader.Find("Raymarch/Raymarch"));
sheet.properties.SetMatrix("_CamFrustum", CamFrustum(_camera));
sheet.properties.SetMatrix("_CamToWorld", _camera.cameraToWorldMatrix);
sheet.properties.SetVector("_CamWorldSpace", _camera.transform.position);
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
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