PostProcessingBehaviour.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Rendering;
  4. namespace UnityEngine.PostProcessing
  5. {
  6. using DebugMode = BuiltinDebugViewsModel.Mode;
  7. #if UNITY_5_4_OR_NEWER
  8. [ImageEffectAllowedInSceneView]
  9. #endif
  10. [RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode]
  11. [AddComponentMenu("Effects/Post-Processing Behaviour", -1)]
  12. public class PostProcessingBehaviour : MonoBehaviour
  13. {
  14. // Inspector fields
  15. public PostProcessingProfile profile;
  16. public Func<Vector2, Matrix4x4> jitteredMatrixFunc;
  17. // Internal helpers
  18. Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>> m_CommandBuffers;
  19. List<PostProcessingComponentBase> m_Components;
  20. Dictionary<PostProcessingComponentBase, bool> m_ComponentStates;
  21. MaterialFactory m_MaterialFactory;
  22. RenderTextureFactory m_RenderTextureFactory;
  23. PostProcessingContext m_Context;
  24. Camera m_Camera;
  25. PostProcessingProfile m_PreviousProfile;
  26. bool m_RenderingInSceneView = false;
  27. // Effect components
  28. BuiltinDebugViewsComponent m_DebugViews;
  29. AmbientOcclusionComponent m_AmbientOcclusion;
  30. ScreenSpaceReflectionComponent m_ScreenSpaceReflection;
  31. FogComponent m_FogComponent;
  32. MotionBlurComponent m_MotionBlur;
  33. TaaComponent m_Taa;
  34. EyeAdaptationComponent m_EyeAdaptation;
  35. DepthOfFieldComponent m_DepthOfField;
  36. BloomComponent m_Bloom;
  37. ChromaticAberrationComponent m_ChromaticAberration;
  38. ColorGradingComponent m_ColorGrading;
  39. UserLutComponent m_UserLut;
  40. GrainComponent m_Grain;
  41. VignetteComponent m_Vignette;
  42. DitheringComponent m_Dithering;
  43. FxaaComponent m_Fxaa;
  44. void OnEnable()
  45. {
  46. m_CommandBuffers = new Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>>();
  47. m_MaterialFactory = new MaterialFactory();
  48. m_RenderTextureFactory = new RenderTextureFactory();
  49. m_Context = new PostProcessingContext();
  50. // Keep a list of all post-fx for automation purposes
  51. m_Components = new List<PostProcessingComponentBase>();
  52. // Component list
  53. m_DebugViews = AddComponent(new BuiltinDebugViewsComponent());
  54. m_AmbientOcclusion = AddComponent(new AmbientOcclusionComponent());
  55. m_ScreenSpaceReflection = AddComponent(new ScreenSpaceReflectionComponent());
  56. m_FogComponent = AddComponent(new FogComponent());
  57. m_MotionBlur = AddComponent(new MotionBlurComponent());
  58. m_Taa = AddComponent(new TaaComponent());
  59. m_EyeAdaptation = AddComponent(new EyeAdaptationComponent());
  60. m_DepthOfField = AddComponent(new DepthOfFieldComponent());
  61. m_Bloom = AddComponent(new BloomComponent());
  62. m_ChromaticAberration = AddComponent(new ChromaticAberrationComponent());
  63. m_ColorGrading = AddComponent(new ColorGradingComponent());
  64. m_UserLut = AddComponent(new UserLutComponent());
  65. m_Grain = AddComponent(new GrainComponent());
  66. m_Vignette = AddComponent(new VignetteComponent());
  67. m_Dithering = AddComponent(new DitheringComponent());
  68. m_Fxaa = AddComponent(new FxaaComponent());
  69. // Prepare state observers
  70. m_ComponentStates = new Dictionary<PostProcessingComponentBase, bool>();
  71. foreach (var component in m_Components)
  72. m_ComponentStates.Add(component, false);
  73. useGUILayout = false;
  74. }
  75. void OnPreCull()
  76. {
  77. // All the per-frame initialization logic has to be done in OnPreCull instead of Update
  78. // because [ImageEffectAllowedInSceneView] doesn't trigger Update events...
  79. m_Camera = GetComponent<Camera>();
  80. if (profile == null || m_Camera == null)
  81. return;
  82. #if UNITY_EDITOR
  83. // Track the scene view camera to disable some effects we don't want to see in the
  84. // scene view
  85. // Currently disabled effects :
  86. // - Temporal Antialiasing
  87. // - Depth of Field
  88. // - Motion blur
  89. m_RenderingInSceneView = UnityEditor.SceneView.currentDrawingSceneView != null
  90. && UnityEditor.SceneView.currentDrawingSceneView.camera == m_Camera;
  91. #endif
  92. // Prepare context
  93. var context = m_Context.Reset();
  94. context.profile = profile;
  95. context.renderTextureFactory = m_RenderTextureFactory;
  96. context.materialFactory = m_MaterialFactory;
  97. context.camera = m_Camera;
  98. // Prepare components
  99. m_DebugViews.Init(context, profile.debugViews);
  100. m_AmbientOcclusion.Init(context, profile.ambientOcclusion);
  101. m_ScreenSpaceReflection.Init(context, profile.screenSpaceReflection);
  102. m_FogComponent.Init(context, profile.fog);
  103. m_MotionBlur.Init(context, profile.motionBlur);
  104. m_Taa.Init(context, profile.antialiasing);
  105. m_EyeAdaptation.Init(context, profile.eyeAdaptation);
  106. m_DepthOfField.Init(context, profile.depthOfField);
  107. m_Bloom.Init(context, profile.bloom);
  108. m_ChromaticAberration.Init(context, profile.chromaticAberration);
  109. m_ColorGrading.Init(context, profile.colorGrading);
  110. m_UserLut.Init(context, profile.userLut);
  111. m_Grain.Init(context, profile.grain);
  112. m_Vignette.Init(context, profile.vignette);
  113. m_Dithering.Init(context, profile.dithering);
  114. m_Fxaa.Init(context, profile.antialiasing);
  115. // Handles profile change and 'enable' state observers
  116. if (m_PreviousProfile != profile)
  117. {
  118. DisableComponents();
  119. m_PreviousProfile = profile;
  120. }
  121. CheckObservers();
  122. // Find out which camera flags are needed before rendering begins
  123. // Note that motion vectors will only be available one frame after being enabled
  124. var flags = DepthTextureMode.None;
  125. foreach (var component in m_Components)
  126. {
  127. if (component.active)
  128. flags |= component.GetCameraFlags();
  129. }
  130. context.camera.depthTextureMode = flags;
  131. // Temporal antialiasing jittering, needs to happen before culling
  132. if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt)
  133. m_Taa.SetProjectionMatrix(jitteredMatrixFunc);
  134. }
  135. void OnPreRender()
  136. {
  137. if (profile == null)
  138. return;
  139. // Command buffer-based effects should be set-up here
  140. TryExecuteCommandBuffer(m_DebugViews);
  141. TryExecuteCommandBuffer(m_AmbientOcclusion);
  142. TryExecuteCommandBuffer(m_ScreenSpaceReflection);
  143. TryExecuteCommandBuffer(m_FogComponent);
  144. if (!m_RenderingInSceneView)
  145. TryExecuteCommandBuffer(m_MotionBlur);
  146. }
  147. void OnPostRender()
  148. {
  149. if (profile == null || m_Camera == null)
  150. return;
  151. if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt)
  152. m_Context.camera.ResetProjectionMatrix();
  153. }
  154. // Classic render target pipeline for RT-based effects
  155. // Note that any effect that happens after this stack will work in LDR
  156. [ImageEffectTransformsToLDR]
  157. void OnRenderImage(RenderTexture source, RenderTexture destination)
  158. {
  159. if (profile == null || m_Camera == null)
  160. {
  161. Graphics.Blit(source, destination);
  162. return;
  163. }
  164. // Uber shader setup
  165. bool uberActive = false;
  166. bool fxaaActive = m_Fxaa.active;
  167. bool taaActive = m_Taa.active && !m_RenderingInSceneView;
  168. bool dofActive = m_DepthOfField.active && !m_RenderingInSceneView;
  169. var uberMaterial = m_MaterialFactory.Get("Hidden/Post FX/Uber Shader");
  170. uberMaterial.shaderKeywords = null;
  171. var src = source;
  172. var dst = destination;
  173. if (taaActive)
  174. {
  175. var tempRT = m_RenderTextureFactory.Get(src);
  176. m_Taa.Render(src, tempRT);
  177. src = tempRT;
  178. }
  179. #if UNITY_EDITOR
  180. // Render to a dedicated target when monitors are enabled so they can show information
  181. // about the final render.
  182. // At runtime the output will always be the backbuffer or whatever render target is
  183. // currently set on the camera.
  184. if (profile.monitors.onFrameEndEditorOnly != null)
  185. dst = m_RenderTextureFactory.Get(src);
  186. #endif
  187. Texture autoExposure = GraphicsUtils.whiteTexture;
  188. if (m_EyeAdaptation.active)
  189. {
  190. uberActive = true;
  191. autoExposure = m_EyeAdaptation.Prepare(src, uberMaterial);
  192. }
  193. uberMaterial.SetTexture("_AutoExposure", autoExposure);
  194. if (dofActive)
  195. {
  196. uberActive = true;
  197. m_DepthOfField.Prepare(src, uberMaterial, taaActive, m_Taa.jitterVector, m_Taa.model.settings.taaSettings.motionBlending);
  198. }
  199. if (m_Bloom.active)
  200. {
  201. uberActive = true;
  202. m_Bloom.Prepare(src, uberMaterial, autoExposure);
  203. }
  204. uberActive |= TryPrepareUberImageEffect(m_ChromaticAberration, uberMaterial);
  205. uberActive |= TryPrepareUberImageEffect(m_ColorGrading, uberMaterial);
  206. uberActive |= TryPrepareUberImageEffect(m_Vignette, uberMaterial);
  207. uberActive |= TryPrepareUberImageEffect(m_UserLut, uberMaterial);
  208. var fxaaMaterial = fxaaActive
  209. ? m_MaterialFactory.Get("Hidden/Post FX/FXAA")
  210. : null;
  211. if (fxaaActive)
  212. {
  213. fxaaMaterial.shaderKeywords = null;
  214. TryPrepareUberImageEffect(m_Grain, fxaaMaterial);
  215. TryPrepareUberImageEffect(m_Dithering, fxaaMaterial);
  216. if (uberActive)
  217. {
  218. var output = m_RenderTextureFactory.Get(src);
  219. Graphics.Blit(src, output, uberMaterial, 0);
  220. src = output;
  221. }
  222. m_Fxaa.Render(src, dst);
  223. }
  224. else
  225. {
  226. uberActive |= TryPrepareUberImageEffect(m_Grain, uberMaterial);
  227. uberActive |= TryPrepareUberImageEffect(m_Dithering, uberMaterial);
  228. if (uberActive)
  229. {
  230. if (!GraphicsUtils.isLinearColorSpace)
  231. uberMaterial.EnableKeyword("UNITY_COLORSPACE_GAMMA");
  232. Graphics.Blit(src, dst, uberMaterial, 0);
  233. }
  234. }
  235. if (!uberActive && !fxaaActive)
  236. Graphics.Blit(src, dst);
  237. #if UNITY_EDITOR
  238. if (profile.monitors.onFrameEndEditorOnly != null)
  239. {
  240. Graphics.Blit(dst, destination);
  241. var oldRt = RenderTexture.active;
  242. profile.monitors.onFrameEndEditorOnly(dst);
  243. RenderTexture.active = oldRt;
  244. }
  245. #endif
  246. m_RenderTextureFactory.ReleaseAll();
  247. }
  248. void OnGUI()
  249. {
  250. if (Event.current.type != EventType.Repaint)
  251. return;
  252. if (profile == null || m_Camera == null)
  253. return;
  254. if (m_EyeAdaptation.active && profile.debugViews.IsModeActive(DebugMode.EyeAdaptation))
  255. m_EyeAdaptation.OnGUI();
  256. else if (m_ColorGrading.active && profile.debugViews.IsModeActive(DebugMode.LogLut))
  257. m_ColorGrading.OnGUI();
  258. else if (m_UserLut.active && profile.debugViews.IsModeActive(DebugMode.UserLut))
  259. m_UserLut.OnGUI();
  260. }
  261. void OnDisable()
  262. {
  263. // Clear command buffers
  264. foreach (var cb in m_CommandBuffers.Values)
  265. {
  266. m_Camera.RemoveCommandBuffer(cb.Key, cb.Value);
  267. cb.Value.Dispose();
  268. }
  269. m_CommandBuffers.Clear();
  270. // Clear components
  271. if (profile != null)
  272. DisableComponents();
  273. m_Components.Clear();
  274. // Reset camera mode
  275. if (m_Camera != null)
  276. m_Camera.depthTextureMode = DepthTextureMode.None;
  277. // Factories
  278. m_MaterialFactory.Dispose();
  279. m_RenderTextureFactory.Dispose();
  280. GraphicsUtils.Dispose();
  281. }
  282. public void ResetTemporalEffects()
  283. {
  284. m_Taa.ResetHistory();
  285. m_MotionBlur.ResetHistory();
  286. m_EyeAdaptation.ResetHistory();
  287. }
  288. #region State management
  289. List<PostProcessingComponentBase> m_ComponentsToEnable = new List<PostProcessingComponentBase>();
  290. List<PostProcessingComponentBase> m_ComponentsToDisable = new List<PostProcessingComponentBase>();
  291. void CheckObservers()
  292. {
  293. foreach (var cs in m_ComponentStates)
  294. {
  295. var component = cs.Key;
  296. var state = component.GetModel().enabled;
  297. if (state != cs.Value)
  298. {
  299. if (state) m_ComponentsToEnable.Add(component);
  300. else m_ComponentsToDisable.Add(component);
  301. }
  302. }
  303. for (int i = 0; i < m_ComponentsToDisable.Count; i++)
  304. {
  305. var c = m_ComponentsToDisable[i];
  306. m_ComponentStates[c] = false;
  307. c.OnDisable();
  308. }
  309. for (int i = 0; i < m_ComponentsToEnable.Count; i++)
  310. {
  311. var c = m_ComponentsToEnable[i];
  312. m_ComponentStates[c] = true;
  313. c.OnEnable();
  314. }
  315. m_ComponentsToDisable.Clear();
  316. m_ComponentsToEnable.Clear();
  317. }
  318. void DisableComponents()
  319. {
  320. foreach (var component in m_Components)
  321. {
  322. var model = component.GetModel();
  323. if (model != null && model.enabled)
  324. component.OnDisable();
  325. }
  326. }
  327. #endregion
  328. #region Command buffer handling & rendering helpers
  329. // Placeholders before the upcoming Scriptable Render Loop as command buffers will be
  330. // executed on the go so we won't need of all that stuff
  331. CommandBuffer AddCommandBuffer<T>(CameraEvent evt, string name)
  332. where T : PostProcessingModel
  333. {
  334. var cb = new CommandBuffer { name = name };
  335. var kvp = new KeyValuePair<CameraEvent, CommandBuffer>(evt, cb);
  336. m_CommandBuffers.Add(typeof(T), kvp);
  337. m_Camera.AddCommandBuffer(evt, kvp.Value);
  338. return kvp.Value;
  339. }
  340. void RemoveCommandBuffer<T>()
  341. where T : PostProcessingModel
  342. {
  343. KeyValuePair<CameraEvent, CommandBuffer> kvp;
  344. var type = typeof(T);
  345. if (!m_CommandBuffers.TryGetValue(type, out kvp))
  346. return;
  347. m_Camera.RemoveCommandBuffer(kvp.Key, kvp.Value);
  348. m_CommandBuffers.Remove(type);
  349. kvp.Value.Dispose();
  350. }
  351. CommandBuffer GetCommandBuffer<T>(CameraEvent evt, string name)
  352. where T : PostProcessingModel
  353. {
  354. CommandBuffer cb;
  355. KeyValuePair<CameraEvent, CommandBuffer> kvp;
  356. if (!m_CommandBuffers.TryGetValue(typeof(T), out kvp))
  357. {
  358. cb = AddCommandBuffer<T>(evt, name);
  359. }
  360. else if (kvp.Key != evt)
  361. {
  362. RemoveCommandBuffer<T>();
  363. cb = AddCommandBuffer<T>(evt, name);
  364. }
  365. else cb = kvp.Value;
  366. return cb;
  367. }
  368. void TryExecuteCommandBuffer<T>(PostProcessingComponentCommandBuffer<T> component)
  369. where T : PostProcessingModel
  370. {
  371. if (component.active)
  372. {
  373. var cb = GetCommandBuffer<T>(component.GetCameraEvent(), component.GetName());
  374. cb.Clear();
  375. component.PopulateCommandBuffer(cb);
  376. }
  377. else RemoveCommandBuffer<T>();
  378. }
  379. bool TryPrepareUberImageEffect<T>(PostProcessingComponentRenderTexture<T> component, Material material)
  380. where T : PostProcessingModel
  381. {
  382. if (!component.active)
  383. return false;
  384. component.Prepare(material);
  385. return true;
  386. }
  387. T AddComponent<T>(T component)
  388. where T : PostProcessingComponentBase
  389. {
  390. m_Components.Add(component);
  391. return component;
  392. }
  393. #endregion
  394. }
  395. }