1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
| using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering;
[ExecuteInEditMode] public class PlanarReflection : MonoBehaviour { public LayerMask _reflectionMask = -1; public bool _reflectSkybox = false; public float _clipPlaneOffset = 0.07F; const string _reflectionTex = "_ReflectionTex"; Camera _reflectionCamera; Vector3 _oldpos; RenderTexture _bluredReflectionTexture; Material _sharedMaterial; public bool _blurOn = true; [Range(0.0f, 5.0f)] public float _blurSize = 1; [Range(0, 10)] public int _blurIterations = 2; [Range(1.0f, 4.0f)] public float _downsample = 1; private bool _oldBlurOn; private float _oldBlurSize; private int _oldBlurIterations; private float _oldDownsample; private Shader _blurShader; private Material _blurMaterial; private static bool _insideRendering;
Material BlurMaterial { get { if (_blurMaterial == null) { _blurMaterial = new Material(_blurShader); return _blurMaterial; } return _blurMaterial; } }
void Awake() { _oldBlurOn = _blurOn; _oldBlurSize = _blurSize; _oldBlurIterations = _blurIterations; _oldDownsample = _downsample; }
void Start() { _sharedMaterial = GetComponent<MeshRenderer>().sharedMaterial; _blurShader = Shader.Find("Hidden/KawaseBlur"); if (_blurShader == null) Debug.LogError("缺少Hidden/KawaseBlur Shader"); }
bool _blurParamChanged; void Update() { if (_blurParamChanged) { _oldBlurOn = _blurOn; _oldBlurSize = _blurSize; _oldBlurIterations = _blurIterations; _oldDownsample = _downsample; }
if (_blurOn != _oldBlurOn || _blurSize != _oldBlurSize || _blurIterations != _oldBlurIterations || _downsample!= _oldDownsample) { _blurParamChanged = true; } }
Camera CreateReflectionCamera(Camera cam) { String reflName = gameObject.name + "Reflection" + cam.name; GameObject go = new GameObject(reflName); go.hideFlags = HideFlags.HideAndDontSave; Camera reflectCamera = go.AddComponent<Camera>(); HoldCameraSettings(reflectCamera); if (!reflectCamera.targetTexture) { reflectCamera.targetTexture = CreateTexture(cam); }
return reflectCamera; } void HoldCameraSettings(Camera heplerCam) { heplerCam.backgroundColor = Color.black; heplerCam.clearFlags = _reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor; heplerCam.renderingPath = RenderingPath.Forward; heplerCam.cullingMask = _reflectionMask; heplerCam.allowMSAA = false; heplerCam.enabled = false; } RenderTexture CreateTexture(Camera sourceCam) { int width = Mathf.RoundToInt(Screen.width / _downsample); int height = Mathf.RoundToInt(Screen.height / _downsample); RenderTextureFormat formatRT = sourceCam.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; RenderTexture rt = new RenderTexture(width, height, 24, formatRT); rt.hideFlags = HideFlags.DontSave; return rt; } void OnWillRenderObject() { Camera currentCam = Camera.current; if (currentCam == null) { return; }
#if !UNITY_EDITOR if (!currentCam.gameObject.CompareTag("MainCamera")) return; #endif
if (_insideRendering) { return; } _insideRendering = true;
if (_reflectionCamera == null) { _reflectionCamera = CreateReflectionCamera(currentCam); }
RenderReflection(currentCam, _reflectionCamera);
if (_reflectionCamera && _sharedMaterial) { if (_blurOn) { if (_bluredReflectionTexture == null) _bluredReflectionTexture = CreateTexture(currentCam); PostProcessTexture(currentCam, _reflectionCamera.targetTexture, _bluredReflectionTexture); _sharedMaterial.SetTexture(_reflectionTex, _bluredReflectionTexture); } else { _sharedMaterial.SetTexture(_reflectionTex, _reflectionCamera.targetTexture); } }
_insideRendering = false; }
void RenderReflection(Camera currentCam, Camera reflectCamera) { if (reflectCamera == null) { Debug.LogError("反射Camera无效"); return; } if (_sharedMaterial && !_sharedMaterial.HasProperty(_reflectionTex)) { Debug.LogError("Shader中缺少_ReflectionTex属性"); return; } HoldCameraSettings(reflectCamera);
if (_reflectSkybox) { if (currentCam.gameObject.GetComponent(typeof(Skybox))) { Skybox sb = (Skybox)reflectCamera.gameObject.GetComponent(typeof(Skybox)); if (!sb) { sb = (Skybox)reflectCamera.gameObject.AddComponent(typeof(Skybox)); } sb.material = ((Skybox)currentCam.GetComponent(typeof(Skybox))).material; } }
bool isInvertCulling = GL.invertCulling; GL.invertCulling = true;
Transform reflectiveSurface = this.transform;
Vector3 eulerA = currentCam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z); reflectCamera.transform.position = currentCam.transform.position;
Vector3 pos = reflectiveSurface.transform.position; pos.y = reflectiveSurface.position.y; Vector3 normal = reflectiveSurface.transform.up; float d = -Vector3.Dot(normal, pos) - _clipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero; reflection = CalculateReflectionMatrix(reflection, reflectionPlane); _oldpos = currentCam.transform.position; Vector3 newpos = reflection.MultiplyPoint(_oldpos);
reflectCamera.worldToCameraMatrix = currentCam.worldToCameraMatrix * reflection;
Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f);
Matrix4x4 projection = currentCam.projectionMatrix; projection = CalculateObliqueMatrix(projection, clipPlane); reflectCamera.projectionMatrix = projection;
reflectCamera.transform.position = newpos; Vector3 euler = currentCam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
reflectCamera.Render();
GL.invertCulling = isInvertCulling; }
static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane) { Vector4 q = projection.inverse * new Vector4( Mathf.Sign(clipPlane.x), Mathf.Sign(clipPlane.y), 1.0F, 1.0F ); Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q))); projection[2] = c.x - projection[3]; projection[6] = c.y - projection[7]; projection[10] = c.z - projection[11]; projection[14] = c.w - projection[15];
return projection; }
static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1.0F - 2.0F * plane[0] * plane[0]); reflectionMat.m01 = (-2.0F * plane[0] * plane[1]); reflectionMat.m02 = (-2.0F * plane[0] * plane[2]); reflectionMat.m03 = (-2.0F * plane[3] * plane[0]);
reflectionMat.m10 = (-2.0F * plane[1] * plane[0]); reflectionMat.m11 = (1.0F - 2.0F * plane[1] * plane[1]); reflectionMat.m12 = (-2.0F * plane[1] * plane[2]); reflectionMat.m13 = (-2.0F * plane[3] * plane[1]);
reflectionMat.m20 = (-2.0F * plane[2] * plane[0]); reflectionMat.m21 = (-2.0F * plane[2] * plane[1]); reflectionMat.m22 = (1.0F - 2.0F * plane[2] * plane[2]); reflectionMat.m23 = (-2.0F * plane[3] * plane[2]);
reflectionMat.m30 = 0.0F; reflectionMat.m31 = 0.0F; reflectionMat.m32 = 0.0F; reflectionMat.m33 = 1.0F;
return reflectionMat; }
Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign) { Vector3 offsetPos = pos + normal * _clipPlaneOffset; Matrix4x4 m = cam.worldToCameraMatrix; Vector3 cpos = m.MultiplyPoint(offsetPos); Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;
return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal)); }
private Dictionary<Camera, CommandBuffer> _cameras = new Dictionary<Camera, CommandBuffer>(); void PostProcessTexture(Camera cam, RenderTexture source, RenderTexture dest) { if (_blurParamChanged) { if (_cameras.ContainsKey(cam)) cam.RemoveCommandBuffer(CameraEvent.BeforeForwardOpaque, _cameras[cam]); _cameras.Remove(cam); } if (_cameras.ContainsKey(cam)) return;
CommandBuffer buf = new CommandBuffer(); buf.name = "Blur Reflection Texture"; _cameras[cam] = buf; float width = source.width; float height = source.height; int rtW = Mathf.RoundToInt(width / _downsample); int rtH = Mathf.RoundToInt(height / _downsample);
int blurredID = Shader.PropertyToID("_Temp1"); int blurredID2 = Shader.PropertyToID("_Temp2"); buf.GetTemporaryRT(blurredID, rtW, rtH, 0, FilterMode.Bilinear, source.format); buf.GetTemporaryRT(blurredID2, rtW, rtH, 0, FilterMode.Bilinear, source.format);
buf.Blit((Texture)source, blurredID); for (int i = 0; i < _blurIterations; i++) { float iterationOffs = (i * 1.0f); buf.SetGlobalFloat("_Offset", iterationOffs / _downsample + _blurSize); buf.Blit(blurredID, blurredID2, BlurMaterial, 0); buf.Blit(blurredID2, blurredID, BlurMaterial, 0); } buf.Blit(blurredID, dest);
buf.ReleaseTemporaryRT(blurredID); buf.ReleaseTemporaryRT(blurredID2);
cam.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, buf); }
}
|