using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class RayMarchingCamera : MonoBehaviour { private Matrix4x4 frustumCorners = Matrix4x4.identity; public Material material; public Camera myCamera; public Transform cameraTransform; // Use this for initialization private void Start() { myCamera.depthTextureMode = DepthTextureMode.Depth; } private void OnRenderImage(RenderTexture source, RenderTexture destination) { //field of view float fov = myCamera.fieldOfView; //近裁面距离 float near = myCamera.nearClipPlane; //横纵比 float aspect = myCamera.aspect; //近裁面一半的高度 float halfHeight = near * Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad); //向上和向右的向量 Vector3 toRight = myCamera.transform.right * halfHeight * aspect; Vector3 toTop = myCamera.transform.up * halfHeight; //分别得到相机到近裁面四个角的向量 //depth/dist=near/|topLeft| //dist=depth*(|TL|/near) //scale=|TL|/near Vector3 topLeft = cameraTransform.forward * near + toTop - toRight; float scale = topLeft.magnitude / near; topLeft.Normalize(); topLeft *= scale; Vector3 topRight = cameraTransform.forward * near + toTop + toRight; topRight.Normalize(); topRight *= scale; Vector3 bottomLeft = cameraTransform.forward * near - toTop - toRight; bottomLeft.Normalize(); bottomLeft *= scale; Vector3 bottomRight = cameraTransform.forward * near - toTop + toRight; bottomRight.Normalize(); bottomRight *= scale; //给矩阵赋值 frustumCorners.SetRow(0, bottomLeft); frustumCorners.SetRow(1, bottomRight); frustumCorners.SetRow(2, topRight); frustumCorners.SetRow(3, topLeft); //将向量传给定点着色器,将屏幕画面传个shader material.SetMatrix( "_FrustumCornorsRay" , frustumCorners); material.SetTexture( "_MainTex" , source); Graphics.Blit(source, destination,material,0); } } |