PostProcessLayer.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine.Assertions;
  5. namespace UnityEngine.Rendering.PostProcessing
  6. {
  7. #if UNITY_2017_2_OR_NEWER
  8. using XRSettings = UnityEngine.XR.XRSettings;
  9. #elif UNITY_5_6_OR_NEWER
  10. using XRSettings = UnityEngine.VR.VRSettings;
  11. #endif
  12. /// <summary>
  13. /// This is the component responsible for rendering post-processing effects. It must be put on
  14. /// every camera you want post-processing to be applied to.
  15. /// </summary>
  16. #if UNITY_2018_3_OR_NEWER
  17. [ExecuteAlways]
  18. #else
  19. [ExecuteInEditMode]
  20. #endif
  21. [DisallowMultipleComponent, ImageEffectAllowedInSceneView]
  22. [AddComponentMenu("Rendering/Post-process Layer", 1000)]
  23. [RequireComponent(typeof(Camera))]
  24. public sealed class PostProcessLayer : MonoBehaviour
  25. {
  26. /// <summary>
  27. /// Builtin anti-aliasing methods.
  28. /// </summary>
  29. public enum Antialiasing
  30. {
  31. /// <summary>
  32. /// No anti-aliasing.
  33. /// </summary>
  34. None,
  35. /// <summary>
  36. /// Fast Approximate Anti-aliasing (FXAA). Fast but low quality.
  37. /// </summary>
  38. FastApproximateAntialiasing,
  39. /// <summary>
  40. /// Subpixel Morphological Anti-aliasing (SMAA). Slower but higher quality than FXAA.
  41. /// </summary>
  42. SubpixelMorphologicalAntialiasing,
  43. /// <summary>
  44. /// Temporal Anti-aliasing (TAA). As fast as SMAA but generally higher quality. Because
  45. /// of it's temporal nature, it can introduce ghosting artifacts on fast moving objects
  46. /// in highly contrasted areas.
  47. /// </summary>
  48. TemporalAntialiasing
  49. }
  50. /// <summary>
  51. /// This is transform that will be drive the volume blending feature. In some cases you may
  52. /// want to use a transform other than the camera, e.g. for a top down game you'll want the
  53. /// player character to drive the blending instead of the actual camera transform.
  54. /// Setting this field to <c>null</c> will disable local volumes for this layer (global ones
  55. /// will still work).
  56. /// </summary>
  57. public Transform volumeTrigger;
  58. /// <summary>
  59. /// A mask of layers to consider for volume blending. It allows you to do volume filtering
  60. /// and is especially useful to optimize volume traversal. You should always have your
  61. /// volumes in dedicated layers instead of the default one for best performances.
  62. /// </summary>
  63. public LayerMask volumeLayer;
  64. /// <summary>
  65. /// If <c>true</c>, it will kill any invalid / NaN pixel and replace it with a black color
  66. /// before post-processing is applied. It's generally a good idea to keep this enabled to
  67. /// avoid post-processing artifacts cause by broken data in the scene.
  68. /// </summary>
  69. public bool stopNaNPropagation = true;
  70. public bool finalBlitToCameraTarget = true;
  71. /// <summary>
  72. /// The anti-aliasing method to use for this camera. By default it's set to <c>None</c>.
  73. /// </summary>
  74. public Antialiasing antialiasingMode = Antialiasing.None;
  75. /// <summary>
  76. /// Temporal Anti-aliasing settings for this camera.
  77. /// </summary>
  78. public TemporalAntialiasing temporalAntialiasing;
  79. /// <summary>
  80. /// Subpixel Morphological Anti-aliasing settings for this camera.
  81. /// </summary>
  82. public SubpixelMorphologicalAntialiasing subpixelMorphologicalAntialiasing;
  83. /// <summary>
  84. /// Fast Approximate Anti-aliasing settings for this camera.
  85. /// </summary>
  86. public FastApproximateAntialiasing fastApproximateAntialiasing;
  87. /// <summary>
  88. /// Fog settings for this camera.
  89. /// </summary>
  90. public Fog fog;
  91. Dithering dithering;
  92. /// <summary>
  93. /// The debug layer is reponsible for rendering debugging information on the screen. It will
  94. /// only be used if this layer is referenced in a <see cref="PostProcessDebug"/> component.
  95. /// </summary>
  96. /// <seealso cref="PostProcessDebug"/>
  97. public PostProcessDebugLayer debugLayer;
  98. [SerializeField]
  99. PostProcessResources m_Resources;
  100. #pragma warning disable 169
  101. // UI states
  102. [SerializeField] bool m_ShowToolkit;
  103. [SerializeField] bool m_ShowCustomSorter;
  104. #pragma warning restore 169
  105. /// <summary>
  106. /// If <c>true</c>, it will stop applying post-processing effects just before color grading
  107. /// is applied. This is used internally to export to EXR without color grading.
  108. /// </summary>
  109. public bool breakBeforeColorGrading = false;
  110. // Pre-ordered custom user effects
  111. // These are automatically populated and made to work properly with the serialization
  112. // system AND the editor. Modify at your own risk.
  113. [Serializable]
  114. public sealed class SerializedBundleRef
  115. {
  116. // We can't serialize Type so use assemblyQualifiedName instead, we only need this at
  117. // init time anyway so it's fine
  118. public string assemblyQualifiedName;
  119. // Not serialized, is set/reset when deserialization kicks in
  120. public PostProcessBundle bundle;
  121. }
  122. [SerializeField]
  123. List<SerializedBundleRef> m_BeforeTransparentBundles;
  124. [SerializeField]
  125. List<SerializedBundleRef> m_BeforeStackBundles;
  126. [SerializeField]
  127. List<SerializedBundleRef> m_AfterStackBundles;
  128. public Dictionary<PostProcessEvent, List<SerializedBundleRef>> sortedBundles { get; private set; }
  129. // We need to keep track of bundle initialization because for some obscure reason, on
  130. // assembly reload a MonoBehavior's Editor OnEnable will be called BEFORE the MonoBehavior's
  131. // own OnEnable... So we'll use it to pre-init bundles if the layer inspector is opened and
  132. // the component hasn't been enabled yet.
  133. public bool haveBundlesBeenInited { get; private set; }
  134. // Settings/Renderer bundles mapped to settings types
  135. Dictionary<Type, PostProcessBundle> m_Bundles;
  136. PropertySheetFactory m_PropertySheetFactory;
  137. CommandBuffer m_LegacyCmdBufferBeforeReflections;
  138. CommandBuffer m_LegacyCmdBufferBeforeLighting;
  139. CommandBuffer m_LegacyCmdBufferOpaque;
  140. CommandBuffer m_LegacyCmdBuffer;
  141. Camera m_Camera;
  142. PostProcessRenderContext m_CurrentContext;
  143. LogHistogram m_LogHistogram;
  144. bool m_SettingsUpdateNeeded = true;
  145. bool m_IsRenderingInSceneView = false;
  146. TargetPool m_TargetPool;
  147. bool m_NaNKilled = false;
  148. // Recycled list - used to reduce GC stress when gathering active effects in a bundle list
  149. // on each frame
  150. readonly List<PostProcessEffectRenderer> m_ActiveEffects = new List<PostProcessEffectRenderer>();
  151. readonly List<RenderTargetIdentifier> m_Targets = new List<RenderTargetIdentifier>();
  152. void OnEnable()
  153. {
  154. Init(null);
  155. if (!haveBundlesBeenInited)
  156. InitBundles();
  157. m_LogHistogram = new LogHistogram();
  158. m_PropertySheetFactory = new PropertySheetFactory();
  159. m_TargetPool = new TargetPool();
  160. debugLayer.OnEnable();
  161. if (RuntimeUtilities.scriptableRenderPipelineActive)
  162. return;
  163. InitLegacy();
  164. }
  165. void InitLegacy()
  166. {
  167. m_LegacyCmdBufferBeforeReflections = new CommandBuffer { name = "Deferred Ambient Occlusion" };
  168. m_LegacyCmdBufferBeforeLighting = new CommandBuffer { name = "Deferred Ambient Occlusion" };
  169. m_LegacyCmdBufferOpaque = new CommandBuffer { name = "Opaque Only Post-processing" };
  170. m_LegacyCmdBuffer = new CommandBuffer { name = "Post-processing" };
  171. m_Camera = GetComponent<Camera>();
  172. #if !UNITY_2019_1_OR_NEWER // OnRenderImage (below) implies forceIntoRenderTexture
  173. m_Camera.forceIntoRenderTexture = true; // Needed when running Forward / LDR / No MSAA
  174. #endif
  175. m_Camera.AddCommandBuffer(CameraEvent.BeforeReflections, m_LegacyCmdBufferBeforeReflections);
  176. m_Camera.AddCommandBuffer(CameraEvent.BeforeLighting, m_LegacyCmdBufferBeforeLighting);
  177. m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_LegacyCmdBufferOpaque);
  178. m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, m_LegacyCmdBuffer);
  179. // Internal context used if no SRP is set
  180. m_CurrentContext = new PostProcessRenderContext();
  181. }
  182. #if UNITY_2019_1_OR_NEWER
  183. // We always use a CommandBuffer to blit to the final render target
  184. // OnRenderImage is used only to avoid the automatic blit from the RenderTexture of Camera.forceIntoRenderTexture to the actual target
  185. [ImageEffectUsesCommandBuffer]
  186. void OnRenderImage(RenderTexture src, RenderTexture dst)
  187. {
  188. if (finalBlitToCameraTarget)
  189. RenderTexture.active = dst; // silence warning
  190. else
  191. Graphics.Blit(src, dst);
  192. }
  193. #endif
  194. /// <summary>
  195. /// Initializes this layer. If you create the layer via scripting you should always call
  196. /// this method.
  197. /// </summary>
  198. /// <param name="resources">A reference to the resource asset</param>
  199. public void Init(PostProcessResources resources)
  200. {
  201. if (resources != null) m_Resources = resources;
  202. RuntimeUtilities.CreateIfNull(ref temporalAntialiasing);
  203. RuntimeUtilities.CreateIfNull(ref subpixelMorphologicalAntialiasing);
  204. RuntimeUtilities.CreateIfNull(ref fastApproximateAntialiasing);
  205. RuntimeUtilities.CreateIfNull(ref dithering);
  206. RuntimeUtilities.CreateIfNull(ref fog);
  207. RuntimeUtilities.CreateIfNull(ref debugLayer);
  208. }
  209. public void InitBundles()
  210. {
  211. if (haveBundlesBeenInited)
  212. return;
  213. // Create these lists only once, the serialization system will take over after that
  214. RuntimeUtilities.CreateIfNull(ref m_BeforeTransparentBundles);
  215. RuntimeUtilities.CreateIfNull(ref m_BeforeStackBundles);
  216. RuntimeUtilities.CreateIfNull(ref m_AfterStackBundles);
  217. // Create a bundle for each effect type
  218. m_Bundles = new Dictionary<Type, PostProcessBundle>();
  219. foreach (var type in PostProcessManager.instance.settingsTypes.Keys)
  220. {
  221. var settings = (PostProcessEffectSettings)ScriptableObject.CreateInstance(type);
  222. var bundle = new PostProcessBundle(settings);
  223. m_Bundles.Add(type, bundle);
  224. }
  225. // Update sorted lists with newly added or removed effects in the assemblies
  226. UpdateBundleSortList(m_BeforeTransparentBundles, PostProcessEvent.BeforeTransparent);
  227. UpdateBundleSortList(m_BeforeStackBundles, PostProcessEvent.BeforeStack);
  228. UpdateBundleSortList(m_AfterStackBundles, PostProcessEvent.AfterStack);
  229. // Push all sorted lists in a dictionary for easier access
  230. sortedBundles = new Dictionary<PostProcessEvent, List<SerializedBundleRef>>(new PostProcessEventComparer())
  231. {
  232. { PostProcessEvent.BeforeTransparent, m_BeforeTransparentBundles },
  233. { PostProcessEvent.BeforeStack, m_BeforeStackBundles },
  234. { PostProcessEvent.AfterStack, m_AfterStackBundles }
  235. };
  236. // Done
  237. haveBundlesBeenInited = true;
  238. }
  239. void UpdateBundleSortList(List<SerializedBundleRef> sortedList, PostProcessEvent evt)
  240. {
  241. // First get all effects associated with the injection point
  242. var effects = m_Bundles.Where(kvp => kvp.Value.attribute.eventType == evt && !kvp.Value.attribute.builtinEffect)
  243. .Select(kvp => kvp.Value)
  244. .ToList();
  245. // Remove types that don't exist anymore
  246. sortedList.RemoveAll(x =>
  247. {
  248. string searchStr = x.assemblyQualifiedName;
  249. return !effects.Exists(b => b.settings.GetType().AssemblyQualifiedName == searchStr);
  250. });
  251. // Add new ones
  252. foreach (var effect in effects)
  253. {
  254. string typeName = effect.settings.GetType().AssemblyQualifiedName;
  255. if (!sortedList.Exists(b => b.assemblyQualifiedName == typeName))
  256. {
  257. var sbr = new SerializedBundleRef { assemblyQualifiedName = typeName };
  258. sortedList.Add(sbr);
  259. }
  260. }
  261. // Link internal references
  262. foreach (var effect in sortedList)
  263. {
  264. string typeName = effect.assemblyQualifiedName;
  265. var bundle = effects.Find(b => b.settings.GetType().AssemblyQualifiedName == typeName);
  266. effect.bundle = bundle;
  267. }
  268. }
  269. void OnDisable()
  270. {
  271. // Have to check for null camera in case the user is doing back'n'forth between SRP and
  272. // legacy
  273. if (m_Camera != null)
  274. {
  275. if (m_LegacyCmdBufferBeforeReflections != null)
  276. m_Camera.RemoveCommandBuffer(CameraEvent.BeforeReflections, m_LegacyCmdBufferBeforeReflections);
  277. if (m_LegacyCmdBufferBeforeLighting != null)
  278. m_Camera.RemoveCommandBuffer(CameraEvent.BeforeLighting, m_LegacyCmdBufferBeforeLighting);
  279. if (m_LegacyCmdBufferOpaque != null)
  280. m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_LegacyCmdBufferOpaque);
  281. if (m_LegacyCmdBuffer != null)
  282. m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffects, m_LegacyCmdBuffer);
  283. }
  284. temporalAntialiasing.Release();
  285. m_LogHistogram.Release();
  286. foreach (var bundle in m_Bundles.Values)
  287. bundle.Release();
  288. m_Bundles.Clear();
  289. m_PropertySheetFactory.Release();
  290. if (debugLayer != null)
  291. debugLayer.OnDisable();
  292. // Might be an issue if several layers are blending in the same frame...
  293. TextureLerper.instance.Clear();
  294. haveBundlesBeenInited = false;
  295. }
  296. // Called everytime the user resets the component from the inspector and more importantly
  297. // the first time it's added to a GameObject. As we don't have added/removed event for
  298. // components, this will do fine
  299. void Reset()
  300. {
  301. volumeTrigger = transform;
  302. }
  303. void OnPreCull()
  304. {
  305. // Unused in scriptable render pipelines
  306. if (RuntimeUtilities.scriptableRenderPipelineActive)
  307. return;
  308. if (m_Camera == null || m_CurrentContext == null)
  309. InitLegacy();
  310. // Resets the projection matrix from previous frame in case TAA was enabled.
  311. // We also need to force reset the non-jittered projection matrix here as it's not done
  312. // when ResetProjectionMatrix() is called and will break transparent rendering if TAA
  313. // is switched off and the FOV or any other camera property changes.
  314. #if UNITY_2018_2_OR_NEWER
  315. if (!m_Camera.usePhysicalProperties)
  316. #endif
  317. m_Camera.ResetProjectionMatrix();
  318. m_Camera.nonJitteredProjectionMatrix = m_Camera.projectionMatrix;
  319. #if !UNITY_SWITCH
  320. if (m_Camera.stereoEnabled)
  321. {
  322. m_Camera.ResetStereoProjectionMatrices();
  323. Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, XRSettings.renderViewportScale);
  324. }
  325. else
  326. #endif
  327. {
  328. Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, 1.0f);
  329. }
  330. BuildCommandBuffers();
  331. }
  332. void OnPreRender()
  333. {
  334. // Unused in scriptable render pipelines
  335. // Only needed for multi-pass stereo right eye
  336. if (RuntimeUtilities.scriptableRenderPipelineActive ||
  337. (m_Camera.stereoActiveEye != Camera.MonoOrStereoscopicEye.Right))
  338. return;
  339. BuildCommandBuffers();
  340. }
  341. static bool RequiresInitialBlit(Camera camera, PostProcessRenderContext context)
  342. {
  343. #if UNITY_2019_1_OR_NEWER
  344. if (camera.allowMSAA) // this shouldn't be necessary, but until re-tested on older Unity versions just do the blits
  345. return true;
  346. if (RuntimeUtilities.scriptableRenderPipelineActive) // Should never be called from SRP
  347. return true;
  348. return false;
  349. #else
  350. return true;
  351. #endif
  352. }
  353. void UpdateSrcDstForOpaqueOnly(ref int src, ref int dst, PostProcessRenderContext context, RenderTargetIdentifier cameraTarget, int opaqueOnlyEffectsRemaining)
  354. {
  355. if (src > -1)
  356. context.command.ReleaseTemporaryRT(src);
  357. context.source = context.destination;
  358. src = dst;
  359. if (opaqueOnlyEffectsRemaining == 1)
  360. {
  361. context.destination = cameraTarget;
  362. }
  363. else
  364. {
  365. dst = m_TargetPool.Get();
  366. context.destination = dst;
  367. context.GetScreenSpaceTemporaryRT(context.command, dst, 0, context.sourceFormat);
  368. }
  369. }
  370. void BuildCommandBuffers()
  371. {
  372. var context = m_CurrentContext;
  373. var sourceFormat = m_Camera.allowHDR ? RuntimeUtilities.defaultHDRRenderTextureFormat : RenderTextureFormat.Default;
  374. if (!RuntimeUtilities.isFloatingPointFormat(sourceFormat))
  375. m_NaNKilled = true;
  376. context.Reset();
  377. context.camera = m_Camera;
  378. context.sourceFormat = sourceFormat;
  379. // TODO: Investigate retaining command buffers on XR multi-pass right eye
  380. m_LegacyCmdBufferBeforeReflections.Clear();
  381. m_LegacyCmdBufferBeforeLighting.Clear();
  382. m_LegacyCmdBufferOpaque.Clear();
  383. m_LegacyCmdBuffer.Clear();
  384. SetupContext(context);
  385. context.command = m_LegacyCmdBufferOpaque;
  386. TextureLerper.instance.BeginFrame(context);
  387. UpdateVolumeSystem(context.camera, context.command);
  388. // Lighting & opaque-only effects
  389. var aoBundle = GetBundle<AmbientOcclusion>();
  390. var aoSettings = aoBundle.CastSettings<AmbientOcclusion>();
  391. var aoRenderer = aoBundle.CastRenderer<AmbientOcclusionRenderer>();
  392. bool aoSupported = aoSettings.IsEnabledAndSupported(context);
  393. bool aoAmbientOnly = aoRenderer.IsAmbientOnly(context);
  394. bool isAmbientOcclusionDeferred = aoSupported && aoAmbientOnly;
  395. bool isAmbientOcclusionOpaque = aoSupported && !aoAmbientOnly;
  396. var ssrBundle = GetBundle<ScreenSpaceReflections>();
  397. var ssrSettings = ssrBundle.settings;
  398. var ssrRenderer = ssrBundle.renderer;
  399. bool isScreenSpaceReflectionsActive = ssrSettings.IsEnabledAndSupported(context);
  400. // Ambient-only AO is a special case and has to be done in separate command buffers
  401. if (isAmbientOcclusionDeferred)
  402. {
  403. var ao = aoRenderer.Get();
  404. // Render as soon as possible - should be done async in SRPs when available
  405. context.command = m_LegacyCmdBufferBeforeReflections;
  406. ao.RenderAmbientOnly(context);
  407. // Composite with GBuffer right before the lighting pass
  408. context.command = m_LegacyCmdBufferBeforeLighting;
  409. ao.CompositeAmbientOnly(context);
  410. }
  411. else if (isAmbientOcclusionOpaque)
  412. {
  413. context.command = m_LegacyCmdBufferOpaque;
  414. aoRenderer.Get().RenderAfterOpaque(context);
  415. }
  416. bool isFogActive = fog.IsEnabledAndSupported(context);
  417. bool hasCustomOpaqueOnlyEffects = HasOpaqueOnlyEffects(context);
  418. int opaqueOnlyEffects = 0;
  419. opaqueOnlyEffects += isScreenSpaceReflectionsActive ? 1 : 0;
  420. opaqueOnlyEffects += isFogActive ? 1 : 0;
  421. opaqueOnlyEffects += hasCustomOpaqueOnlyEffects ? 1 : 0;
  422. // This works on right eye because it is resolved/populated at runtime
  423. var cameraTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget);
  424. if (opaqueOnlyEffects > 0)
  425. {
  426. var cmd = m_LegacyCmdBufferOpaque;
  427. context.command = cmd;
  428. context.source = cameraTarget;
  429. context.destination = cameraTarget;
  430. int srcTarget = -1;
  431. int dstTarget = -1;
  432. UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects + 1); // + 1 for blit
  433. if (RequiresInitialBlit(m_Camera, context) || opaqueOnlyEffects == 1)
  434. {
  435. cmd.BuiltinBlit(context.source, context.destination, RuntimeUtilities.copyStdMaterial, stopNaNPropagation ? 1 : 0);
  436. UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects);
  437. }
  438. if (isScreenSpaceReflectionsActive)
  439. {
  440. ssrRenderer.Render(context);
  441. opaqueOnlyEffects--;
  442. UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects);
  443. }
  444. if (isFogActive)
  445. {
  446. fog.Render(context);
  447. opaqueOnlyEffects--;
  448. UpdateSrcDstForOpaqueOnly(ref srcTarget, ref dstTarget, context, cameraTarget, opaqueOnlyEffects);
  449. }
  450. if (hasCustomOpaqueOnlyEffects)
  451. RenderOpaqueOnly(context);
  452. cmd.ReleaseTemporaryRT(srcTarget);
  453. }
  454. // Post-transparency stack
  455. int tempRt = -1;
  456. bool forceNanKillPass = (!m_NaNKilled && stopNaNPropagation && RuntimeUtilities.isFloatingPointFormat(sourceFormat));
  457. if (RequiresInitialBlit(m_Camera, context) || forceNanKillPass)
  458. {
  459. tempRt = m_TargetPool.Get();
  460. context.GetScreenSpaceTemporaryRT(m_LegacyCmdBuffer, tempRt, 0, sourceFormat, RenderTextureReadWrite.sRGB);
  461. m_LegacyCmdBuffer.BuiltinBlit(cameraTarget, tempRt, RuntimeUtilities.copyStdMaterial, stopNaNPropagation ? 1 : 0);
  462. if (!m_NaNKilled)
  463. m_NaNKilled = stopNaNPropagation;
  464. context.source = tempRt;
  465. }
  466. else
  467. {
  468. context.source = cameraTarget;
  469. }
  470. context.destination = cameraTarget;
  471. #if UNITY_2019_1_OR_NEWER
  472. if (finalBlitToCameraTarget && !RuntimeUtilities.scriptableRenderPipelineActive)
  473. {
  474. if (m_Camera.targetTexture)
  475. {
  476. context.destination = m_Camera.targetTexture.colorBuffer;
  477. }
  478. else
  479. {
  480. context.flip = true;
  481. context.destination = Display.main.colorBuffer;
  482. }
  483. }
  484. #endif
  485. context.command = m_LegacyCmdBuffer;
  486. Render(context);
  487. if (tempRt > -1)
  488. m_LegacyCmdBuffer.ReleaseTemporaryRT(tempRt);
  489. }
  490. void OnPostRender()
  491. {
  492. // Unused in scriptable render pipelines
  493. if (RuntimeUtilities.scriptableRenderPipelineActive)
  494. return;
  495. if (m_CurrentContext.IsTemporalAntialiasingActive())
  496. {
  497. #if UNITY_2018_2_OR_NEWER
  498. // TAA calls SetProjectionMatrix so if the camera projection mode was physical, it gets set to explicit. So we set it back to physical.
  499. if (m_CurrentContext.physicalCamera)
  500. m_Camera.usePhysicalProperties = true;
  501. else
  502. #endif
  503. m_Camera.ResetProjectionMatrix();
  504. if (m_CurrentContext.stereoActive)
  505. {
  506. if (RuntimeUtilities.isSinglePassStereoEnabled || m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Right)
  507. m_Camera.ResetStereoProjectionMatrices();
  508. }
  509. }
  510. }
  511. public PostProcessBundle GetBundle<T>()
  512. where T : PostProcessEffectSettings
  513. {
  514. return GetBundle(typeof(T));
  515. }
  516. public PostProcessBundle GetBundle(Type settingsType)
  517. {
  518. Assert.IsTrue(m_Bundles.ContainsKey(settingsType), "Invalid type");
  519. return m_Bundles[settingsType];
  520. }
  521. /// <summary>
  522. /// Gets the current settings for a given effect.
  523. /// </summary>
  524. /// <typeparam name="T">The type of effect to look for</typeparam>
  525. /// <returns>The current state of an effect</returns>
  526. public T GetSettings<T>()
  527. where T : PostProcessEffectSettings
  528. {
  529. return GetBundle<T>().CastSettings<T>();
  530. }
  531. /// <summary>
  532. /// Utility method to bake a multi-scale volumetric obscurance map for the current camera.
  533. /// This will only work if ambient occlusion is active in the scene.
  534. /// </summary>
  535. /// <param name="cmd">The command buffer to use for rendering steps</param>
  536. /// <param name="camera">The camera to render ambient occlusion for</param>
  537. /// <param name="destination">The destination render target</param>
  538. /// <param name="depthMap">The depth map to use. If <c>null</c>, it will use the depth map
  539. /// from the given camera</param>
  540. /// <param name="invert">Should the result be inverted?</param>
  541. /// <param name="isMSAA">Should use MSAA?</param>
  542. public void BakeMSVOMap(CommandBuffer cmd, Camera camera, RenderTargetIdentifier destination, RenderTargetIdentifier? depthMap, bool invert, bool isMSAA = false)
  543. {
  544. var bundle = GetBundle<AmbientOcclusion>();
  545. var renderer = bundle.CastRenderer<AmbientOcclusionRenderer>().GetMultiScaleVO();
  546. renderer.SetResources(m_Resources);
  547. renderer.GenerateAOMap(cmd, camera, destination, depthMap, invert, isMSAA);
  548. }
  549. internal void OverrideSettings(List<PostProcessEffectSettings> baseSettings, float interpFactor)
  550. {
  551. // Go through all settings & overriden parameters for the given volume and lerp values
  552. foreach (var settings in baseSettings)
  553. {
  554. if (!settings.active)
  555. continue;
  556. var target = GetBundle(settings.GetType()).settings;
  557. int count = settings.parameters.Count;
  558. for (int i = 0; i < count; i++)
  559. {
  560. var toParam = settings.parameters[i];
  561. if (toParam.overrideState)
  562. {
  563. var fromParam = target.parameters[i];
  564. fromParam.Interp(fromParam, toParam, interpFactor);
  565. }
  566. }
  567. }
  568. }
  569. // In the legacy render loop you have to explicitely set flags on camera to tell that you
  570. // need depth, depth+normals or motion vectors... This won't have any effect with most
  571. // scriptable render pipelines.
  572. void SetLegacyCameraFlags(PostProcessRenderContext context)
  573. {
  574. var flags = context.camera.depthTextureMode;
  575. foreach (var bundle in m_Bundles)
  576. {
  577. if (bundle.Value.settings.IsEnabledAndSupported(context))
  578. flags |= bundle.Value.renderer.GetCameraFlags();
  579. }
  580. // Special case for AA & lighting effects
  581. if (context.IsTemporalAntialiasingActive())
  582. flags |= temporalAntialiasing.GetCameraFlags();
  583. if (fog.IsEnabledAndSupported(context))
  584. flags |= fog.GetCameraFlags();
  585. if (debugLayer.debugOverlay != DebugOverlay.None)
  586. flags |= debugLayer.GetCameraFlags();
  587. context.camera.depthTextureMode = flags;
  588. }
  589. /// <summary>
  590. /// This method should be called whenever you need to reset any temporal effect, e.g. when
  591. /// doing camera cuts.
  592. /// </summary>
  593. public void ResetHistory()
  594. {
  595. foreach (var bundle in m_Bundles)
  596. bundle.Value.ResetHistory();
  597. temporalAntialiasing.ResetHistory();
  598. }
  599. /// <summary>
  600. /// Checks if this layer has any active opaque-only effect.
  601. /// </summary>
  602. /// <param name="context">The current render context</param>
  603. /// <returns><c>true</c> if opaque-only effects are active, <c>false</c> otherwise</returns>
  604. public bool HasOpaqueOnlyEffects(PostProcessRenderContext context)
  605. {
  606. return HasActiveEffects(PostProcessEvent.BeforeTransparent, context);
  607. }
  608. /// <summary>
  609. /// Checks if this layer has any active effect at the given injection point.
  610. /// </summary>
  611. /// <param name="evt">The injection point to look for</param>
  612. /// <param name="context">The current render context</param>
  613. /// <returns><c>true</c> if any effect at the given injection point is active, <c>false</c>
  614. /// otherwise</returns>
  615. public bool HasActiveEffects(PostProcessEvent evt, PostProcessRenderContext context)
  616. {
  617. var list = sortedBundles[evt];
  618. foreach (var item in list)
  619. {
  620. if (item.bundle.settings.IsEnabledAndSupported(context))
  621. return true;
  622. }
  623. return false;
  624. }
  625. void SetupContext(PostProcessRenderContext context)
  626. {
  627. RuntimeUtilities.s_Resources = m_Resources;
  628. m_IsRenderingInSceneView = context.camera.cameraType == CameraType.SceneView;
  629. context.isSceneView = m_IsRenderingInSceneView;
  630. context.resources = m_Resources;
  631. context.propertySheets = m_PropertySheetFactory;
  632. context.debugLayer = debugLayer;
  633. context.antialiasing = antialiasingMode;
  634. context.temporalAntialiasing = temporalAntialiasing;
  635. context.logHistogram = m_LogHistogram;
  636. #if UNITY_2018_2_OR_NEWER
  637. context.physicalCamera = context.camera.usePhysicalProperties;
  638. #endif
  639. SetLegacyCameraFlags(context);
  640. // Prepare debug overlay
  641. debugLayer.SetFrameSize(context.width, context.height);
  642. // Unsafe to keep this around but we need it for OnGUI events for debug views
  643. // Will be removed eventually
  644. m_CurrentContext = context;
  645. }
  646. /// <summary>
  647. /// Updates the state of the volume system. This should be called before any other
  648. /// post-processing method when running in a scriptable render pipeline. You don't need to
  649. /// call this method when running in one of the builtin pipelines.
  650. /// </summary>
  651. /// <param name="cam">The currently rendering camera.</param>
  652. /// <param name="cmd">A command buffer to fill.</param>
  653. public void UpdateVolumeSystem(Camera cam, CommandBuffer cmd)
  654. {
  655. if (m_SettingsUpdateNeeded)
  656. {
  657. cmd.BeginSample("VolumeBlending");
  658. PostProcessManager.instance.UpdateSettings(this, cam);
  659. cmd.EndSample("VolumeBlending");
  660. m_TargetPool.Reset();
  661. // TODO: fix me once VR support is in SRP
  662. // Needed in SRP so that _RenderViewportScaleFactor isn't 0
  663. if (RuntimeUtilities.scriptableRenderPipelineActive)
  664. Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, 1f);
  665. }
  666. m_SettingsUpdateNeeded = false;
  667. }
  668. /// <summary>
  669. /// Renders effects in the <see cref="PostProcessEvent.BeforeTransparent"/> bucket. You
  670. /// should call <see cref="HasOpaqueOnlyEffects"/> before calling this method as it won't
  671. /// automatically blit source into destination if no opaque-only effect is active.
  672. /// </summary>
  673. /// <param name="context">The current post-processing context.</param>
  674. public void RenderOpaqueOnly(PostProcessRenderContext context)
  675. {
  676. if (RuntimeUtilities.scriptableRenderPipelineActive)
  677. SetupContext(context);
  678. TextureLerper.instance.BeginFrame(context);
  679. // Update & override layer settings first (volume blending), will only be done once per
  680. // frame, either here or in Render() if there isn't any opaque-only effect to render.
  681. // TODO: should be removed, keeping this here for older SRPs
  682. UpdateVolumeSystem(context.camera, context.command);
  683. RenderList(sortedBundles[PostProcessEvent.BeforeTransparent], context, "OpaqueOnly");
  684. }
  685. /// <summary>
  686. /// Renders all effects not in the <see cref="PostProcessEvent.BeforeTransparent"/> bucket.
  687. /// </summary>
  688. /// <param name="context">The current post-processing context.</param>
  689. public void Render(PostProcessRenderContext context)
  690. {
  691. if (RuntimeUtilities.scriptableRenderPipelineActive)
  692. SetupContext(context);
  693. TextureLerper.instance.BeginFrame(context);
  694. var cmd = context.command;
  695. // Update & override layer settings first (volume blending) if the opaque only pass
  696. // hasn't been called this frame.
  697. // TODO: should be removed, keeping this here for older SRPs
  698. UpdateVolumeSystem(context.camera, context.command);
  699. // Do a NaN killing pass if needed
  700. int lastTarget = -1;
  701. RenderTargetIdentifier cameraTexture = context.source;
  702. #if UNITY_2019_1_OR_NEWER
  703. if (context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  704. {
  705. cmd.SetSinglePassStereo(SinglePassStereoMode.None);
  706. cmd.DisableShaderKeyword("UNITY_SINGLE_PASS_STEREO");
  707. }
  708. #endif
  709. for (int eye = 0; eye < context.numberOfEyes; eye++)
  710. {
  711. bool preparedStereoSource = false;
  712. if (stopNaNPropagation && !m_NaNKilled)
  713. {
  714. lastTarget = m_TargetPool.Get();
  715. context.GetScreenSpaceTemporaryRT(cmd, lastTarget, 0, context.sourceFormat);
  716. if (context.stereoActive && context.numberOfEyes > 1)
  717. {
  718. if (context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  719. {
  720. cmd.BlitFullscreenTriangleFromTexArray(context.source, lastTarget, RuntimeUtilities.copyFromTexArraySheet, 1, false, eye);
  721. preparedStereoSource = true;
  722. }
  723. else if (context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  724. {
  725. cmd.BlitFullscreenTriangleFromDoubleWide(context.source, lastTarget, RuntimeUtilities.copyStdFromDoubleWideMaterial, 1, eye);
  726. preparedStereoSource = true;
  727. }
  728. }
  729. else
  730. cmd.BlitFullscreenTriangle(context.source, lastTarget, RuntimeUtilities.copySheet, 1);
  731. context.source = lastTarget;
  732. m_NaNKilled = true;
  733. }
  734. if (!preparedStereoSource && context.numberOfEyes > 1)
  735. {
  736. lastTarget = m_TargetPool.Get();
  737. context.GetScreenSpaceTemporaryRT(cmd, lastTarget, 0, context.sourceFormat);
  738. if (context.stereoActive)
  739. {
  740. if (context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  741. {
  742. cmd.BlitFullscreenTriangleFromTexArray(context.source, lastTarget, RuntimeUtilities.copyFromTexArraySheet, 1, false, eye);
  743. preparedStereoSource = true;
  744. }
  745. else if (context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  746. {
  747. cmd.BlitFullscreenTriangleFromDoubleWide(context.source, lastTarget, RuntimeUtilities.copyStdFromDoubleWideMaterial, stopNaNPropagation ? 1 : 0, eye);
  748. preparedStereoSource = true;
  749. }
  750. }
  751. context.source = lastTarget;
  752. }
  753. // Do temporal anti-aliasing first
  754. if (context.IsTemporalAntialiasingActive())
  755. {
  756. if (!RuntimeUtilities.scriptableRenderPipelineActive)
  757. {
  758. if (context.stereoActive)
  759. {
  760. // We only need to configure all of this once for stereo, during OnPreCull
  761. if (context.camera.stereoActiveEye != Camera.MonoOrStereoscopicEye.Right)
  762. temporalAntialiasing.ConfigureStereoJitteredProjectionMatrices(context);
  763. }
  764. else
  765. {
  766. temporalAntialiasing.ConfigureJitteredProjectionMatrix(context);
  767. }
  768. }
  769. var taaTarget = m_TargetPool.Get();
  770. var finalDestination = context.destination;
  771. context.GetScreenSpaceTemporaryRT(cmd, taaTarget, 0, context.sourceFormat);
  772. context.destination = taaTarget;
  773. temporalAntialiasing.Render(context);
  774. context.source = taaTarget;
  775. context.destination = finalDestination;
  776. if (lastTarget > -1)
  777. cmd.ReleaseTemporaryRT(lastTarget);
  778. lastTarget = taaTarget;
  779. }
  780. bool hasBeforeStackEffects = HasActiveEffects(PostProcessEvent.BeforeStack, context);
  781. bool hasAfterStackEffects = HasActiveEffects(PostProcessEvent.AfterStack, context) && !breakBeforeColorGrading;
  782. bool needsFinalPass = (hasAfterStackEffects
  783. || (antialiasingMode == Antialiasing.FastApproximateAntialiasing) || (antialiasingMode == Antialiasing.SubpixelMorphologicalAntialiasing && subpixelMorphologicalAntialiasing.IsSupported()))
  784. && !breakBeforeColorGrading;
  785. // Right before the builtin stack
  786. if (hasBeforeStackEffects)
  787. lastTarget = RenderInjectionPoint(PostProcessEvent.BeforeStack, context, "BeforeStack", lastTarget);
  788. // Builtin stack
  789. lastTarget = RenderBuiltins(context, !needsFinalPass, lastTarget, eye);
  790. // After the builtin stack but before the final pass (before FXAA & Dithering)
  791. if (hasAfterStackEffects)
  792. lastTarget = RenderInjectionPoint(PostProcessEvent.AfterStack, context, "AfterStack", lastTarget);
  793. // And close with the final pass
  794. if (needsFinalPass)
  795. RenderFinalPass(context, lastTarget, eye);
  796. if (context.stereoActive)
  797. context.source = cameraTexture;
  798. }
  799. #if UNITY_2019_1_OR_NEWER
  800. if (context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  801. {
  802. cmd.SetSinglePassStereo(SinglePassStereoMode.SideBySide);
  803. cmd.EnableShaderKeyword("UNITY_SINGLE_PASS_STEREO");
  804. }
  805. #endif
  806. // Render debug monitors & overlay if requested
  807. debugLayer.RenderSpecialOverlays(context);
  808. debugLayer.RenderMonitors(context);
  809. // End frame cleanup
  810. TextureLerper.instance.EndFrame();
  811. debugLayer.EndFrame();
  812. m_SettingsUpdateNeeded = true;
  813. m_NaNKilled = false;
  814. }
  815. int RenderInjectionPoint(PostProcessEvent evt, PostProcessRenderContext context, string marker, int releaseTargetAfterUse = -1)
  816. {
  817. int tempTarget = m_TargetPool.Get();
  818. var finalDestination = context.destination;
  819. var cmd = context.command;
  820. context.GetScreenSpaceTemporaryRT(cmd, tempTarget, 0, context.sourceFormat);
  821. context.destination = tempTarget;
  822. RenderList(sortedBundles[evt], context, marker);
  823. context.source = tempTarget;
  824. context.destination = finalDestination;
  825. if (releaseTargetAfterUse > -1)
  826. cmd.ReleaseTemporaryRT(releaseTargetAfterUse);
  827. return tempTarget;
  828. }
  829. void RenderList(List<SerializedBundleRef> list, PostProcessRenderContext context, string marker)
  830. {
  831. var cmd = context.command;
  832. cmd.BeginSample(marker);
  833. // First gather active effects - we need this to manage render targets more efficiently
  834. m_ActiveEffects.Clear();
  835. for (int i = 0; i < list.Count; i++)
  836. {
  837. var effect = list[i].bundle;
  838. if (effect.settings.IsEnabledAndSupported(context))
  839. {
  840. if (!context.isSceneView || (context.isSceneView && effect.attribute.allowInSceneView))
  841. m_ActiveEffects.Add(effect.renderer);
  842. }
  843. }
  844. int count = m_ActiveEffects.Count;
  845. // If there's only one active effect, we can simply execute it and skip the rest
  846. if (count == 1)
  847. {
  848. m_ActiveEffects[0].Render(context);
  849. }
  850. else
  851. {
  852. // Else create the target chain
  853. m_Targets.Clear();
  854. m_Targets.Add(context.source); // First target is always source
  855. int tempTarget1 = m_TargetPool.Get();
  856. int tempTarget2 = m_TargetPool.Get();
  857. for (int i = 0; i < count - 1; i++)
  858. m_Targets.Add(i % 2 == 0 ? tempTarget1 : tempTarget2);
  859. m_Targets.Add(context.destination); // Last target is always destination
  860. // Render
  861. context.GetScreenSpaceTemporaryRT(cmd, tempTarget1, 0, context.sourceFormat);
  862. if (count > 2)
  863. context.GetScreenSpaceTemporaryRT(cmd, tempTarget2, 0, context.sourceFormat);
  864. for (int i = 0; i < count; i++)
  865. {
  866. context.source = m_Targets[i];
  867. context.destination = m_Targets[i + 1];
  868. m_ActiveEffects[i].Render(context);
  869. }
  870. cmd.ReleaseTemporaryRT(tempTarget1);
  871. if (count > 2)
  872. cmd.ReleaseTemporaryRT(tempTarget2);
  873. }
  874. cmd.EndSample(marker);
  875. }
  876. void ApplyFlip(PostProcessRenderContext context, MaterialPropertyBlock properties)
  877. {
  878. if (context.flip && !context.isSceneView)
  879. properties.SetVector(ShaderIDs.UVTransform, new Vector4(1.0f, 1.0f, 0.0f, 0.0f));
  880. else
  881. ApplyDefaultFlip(properties);
  882. }
  883. void ApplyDefaultFlip(MaterialPropertyBlock properties)
  884. {
  885. properties.SetVector(ShaderIDs.UVTransform, SystemInfo.graphicsUVStartsAtTop ? new Vector4(1.0f, -1.0f, 0.0f, 1.0f) : new Vector4(1.0f, 1.0f, 0.0f, 0.0f));
  886. }
  887. int RenderBuiltins(PostProcessRenderContext context, bool isFinalPass, int releaseTargetAfterUse = -1, int eye = -1)
  888. {
  889. var uberSheet = context.propertySheets.Get(context.resources.shaders.uber);
  890. uberSheet.ClearKeywords();
  891. uberSheet.properties.Clear();
  892. context.uberSheet = uberSheet;
  893. context.autoExposureTexture = RuntimeUtilities.whiteTexture;
  894. context.bloomBufferNameID = -1;
  895. if (isFinalPass && context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  896. uberSheet.EnableKeyword("STEREO_INSTANCING_ENABLED");
  897. var cmd = context.command;
  898. cmd.BeginSample("BuiltinStack");
  899. int tempTarget = -1;
  900. var finalDestination = context.destination;
  901. if (!isFinalPass)
  902. {
  903. // Render to an intermediate target as this won't be the final pass
  904. tempTarget = m_TargetPool.Get();
  905. context.GetScreenSpaceTemporaryRT(cmd, tempTarget, 0, context.sourceFormat);
  906. context.destination = tempTarget;
  907. // Handle FXAA's keep alpha mode
  908. if (antialiasingMode == Antialiasing.FastApproximateAntialiasing && !fastApproximateAntialiasing.keepAlpha)
  909. uberSheet.properties.SetFloat(ShaderIDs.LumaInAlpha, 1f);
  910. }
  911. // Depth of field final combination pass used to be done in Uber which led to artifacts
  912. // when used at the same time as Bloom (because both effects used the same source, so
  913. // the stronger bloom was, the more DoF was eaten away in out of focus areas)
  914. int depthOfFieldTarget = RenderEffect<DepthOfField>(context, true);
  915. // Motion blur is a separate pass - could potentially be done after DoF depending on the
  916. // kind of results you're looking for...
  917. int motionBlurTarget = RenderEffect<MotionBlur>(context, true);
  918. // Prepare exposure histogram if needed
  919. if (ShouldGenerateLogHistogram(context))
  920. m_LogHistogram.Generate(context);
  921. // Uber effects
  922. RenderEffect<AutoExposure>(context);
  923. uberSheet.properties.SetTexture(ShaderIDs.AutoExposureTex, context.autoExposureTexture);
  924. RenderEffect<LensDistortion>(context);
  925. RenderEffect<ChromaticAberration>(context);
  926. RenderEffect<Bloom>(context);
  927. RenderEffect<Vignette>(context);
  928. RenderEffect<Grain>(context);
  929. if (!breakBeforeColorGrading)
  930. RenderEffect<ColorGrading>(context);
  931. if (isFinalPass)
  932. {
  933. uberSheet.EnableKeyword("FINALPASS");
  934. dithering.Render(context);
  935. ApplyFlip(context, uberSheet.properties);
  936. }
  937. else
  938. {
  939. ApplyDefaultFlip(uberSheet.properties);
  940. }
  941. if (context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  942. {
  943. uberSheet.properties.SetFloat(ShaderIDs.DepthSlice, eye);
  944. cmd.BlitFullscreenTriangleToTexArray(context.source, context.destination, uberSheet, 0, false, eye);
  945. }
  946. else if (isFinalPass && context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  947. {
  948. cmd.BlitFullscreenTriangleToDoubleWide(context.source, context.destination, uberSheet, 0, eye);
  949. }
  950. else if (isFinalPass)
  951. cmd.BlitFullscreenTriangle(context.source, context.destination, uberSheet, 0, false, context.camera.pixelRect);
  952. else
  953. cmd.BlitFullscreenTriangle(context.source, context.destination, uberSheet, 0);
  954. context.source = context.destination;
  955. context.destination = finalDestination;
  956. if (releaseTargetAfterUse > -1) cmd.ReleaseTemporaryRT(releaseTargetAfterUse);
  957. if (motionBlurTarget > -1) cmd.ReleaseTemporaryRT(motionBlurTarget);
  958. if (depthOfFieldTarget > -1) cmd.ReleaseTemporaryRT(depthOfFieldTarget);
  959. if (context.bloomBufferNameID > -1) cmd.ReleaseTemporaryRT(context.bloomBufferNameID);
  960. cmd.EndSample("BuiltinStack");
  961. return tempTarget;
  962. }
  963. // This pass will have to be disabled for HDR screen output as it's an LDR pass
  964. void RenderFinalPass(PostProcessRenderContext context, int releaseTargetAfterUse = -1, int eye = -1)
  965. {
  966. var cmd = context.command;
  967. cmd.BeginSample("FinalPass");
  968. if (breakBeforeColorGrading)
  969. {
  970. var sheet = context.propertySheets.Get(context.resources.shaders.discardAlpha);
  971. if (context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  972. sheet.EnableKeyword("STEREO_INSTANCING_ENABLED");
  973. if (context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  974. {
  975. sheet.properties.SetFloat(ShaderIDs.DepthSlice, eye);
  976. cmd.BlitFullscreenTriangleToTexArray(context.source, context.destination, sheet, 0, false, eye);
  977. }
  978. else if (context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  979. {
  980. cmd.BlitFullscreenTriangleToDoubleWide(context.source, context.destination, sheet, 0, eye);
  981. }
  982. else
  983. cmd.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
  984. }
  985. else
  986. {
  987. var uberSheet = context.propertySheets.Get(context.resources.shaders.finalPass);
  988. uberSheet.ClearKeywords();
  989. uberSheet.properties.Clear();
  990. context.uberSheet = uberSheet;
  991. int tempTarget = -1;
  992. if (context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  993. uberSheet.EnableKeyword("STEREO_INSTANCING_ENABLED");
  994. if (antialiasingMode == Antialiasing.FastApproximateAntialiasing)
  995. {
  996. uberSheet.EnableKeyword(fastApproximateAntialiasing.fastMode
  997. ? "FXAA_LOW"
  998. : "FXAA"
  999. );
  1000. if (fastApproximateAntialiasing.keepAlpha)
  1001. uberSheet.EnableKeyword("FXAA_KEEP_ALPHA");
  1002. }
  1003. else if (antialiasingMode == Antialiasing.SubpixelMorphologicalAntialiasing && subpixelMorphologicalAntialiasing.IsSupported())
  1004. {
  1005. tempTarget = m_TargetPool.Get();
  1006. var finalDestination = context.destination;
  1007. context.GetScreenSpaceTemporaryRT(context.command, tempTarget, 0, context.sourceFormat);
  1008. context.destination = tempTarget;
  1009. subpixelMorphologicalAntialiasing.Render(context);
  1010. context.source = tempTarget;
  1011. context.destination = finalDestination;
  1012. }
  1013. dithering.Render(context);
  1014. ApplyFlip(context, uberSheet.properties);
  1015. if (context.stereoActive && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePassInstanced)
  1016. {
  1017. uberSheet.properties.SetFloat(ShaderIDs.DepthSlice, eye);
  1018. cmd.BlitFullscreenTriangleToTexArray(context.source, context.destination, uberSheet, 0, false, eye);
  1019. }
  1020. else if (context.stereoActive && context.numberOfEyes > 1 && context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass)
  1021. {
  1022. cmd.BlitFullscreenTriangleToDoubleWide(context.source, context.destination, uberSheet, 0, eye);
  1023. }
  1024. else
  1025. cmd.BlitFullscreenTriangle(context.source, context.destination, uberSheet, 0, false, context.camera.pixelRect);
  1026. if (tempTarget > -1)
  1027. cmd.ReleaseTemporaryRT(tempTarget);
  1028. }
  1029. if (releaseTargetAfterUse > -1)
  1030. cmd.ReleaseTemporaryRT(releaseTargetAfterUse);
  1031. cmd.EndSample("FinalPass");
  1032. }
  1033. int RenderEffect<T>(PostProcessRenderContext context, bool useTempTarget = false)
  1034. where T : PostProcessEffectSettings
  1035. {
  1036. var effect = GetBundle<T>();
  1037. if (!effect.settings.IsEnabledAndSupported(context))
  1038. return -1;
  1039. if (m_IsRenderingInSceneView && !effect.attribute.allowInSceneView)
  1040. return -1;
  1041. if (!useTempTarget)
  1042. {
  1043. effect.renderer.Render(context);
  1044. return -1;
  1045. }
  1046. var finalDestination = context.destination;
  1047. var tempTarget = m_TargetPool.Get();
  1048. context.GetScreenSpaceTemporaryRT(context.command, tempTarget, 0, context.sourceFormat);
  1049. context.destination = tempTarget;
  1050. effect.renderer.Render(context);
  1051. context.source = tempTarget;
  1052. context.destination = finalDestination;
  1053. return tempTarget;
  1054. }
  1055. bool ShouldGenerateLogHistogram(PostProcessRenderContext context)
  1056. {
  1057. bool autoExpo = GetBundle<AutoExposure>().settings.IsEnabledAndSupported(context);
  1058. bool lightMeter = debugLayer.lightMeter.IsRequestedAndSupported(context);
  1059. return autoExpo || lightMeter;
  1060. }
  1061. }
  1062. }