暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Renderer2DRendergraph.cs 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. using UnityEngine.Experimental.Rendering;
  2. using UnityEngine.Rendering.RenderGraphModule;
  3. using static UnityEngine.Rendering.Universal.UniversalResourceDataBase;
  4. using CommonResourceData = UnityEngine.Rendering.Universal.UniversalResourceData;
  5. namespace UnityEngine.Rendering.Universal
  6. {
  7. internal enum Renderer2DResource
  8. {
  9. BackBufferColor,
  10. BackBufferDepth,
  11. // intermediate camera targets
  12. CameraColor,
  13. CameraDepth,
  14. // intermediate depth for usage in passes with render texture scale
  15. IntermediateDepth,
  16. LightTexture0,
  17. LightTexture1,
  18. LightTexture2,
  19. LightTexture3,
  20. NormalsTexture,
  21. ShadowsTexture,
  22. UpscaleTexture,
  23. CameraSortingLayerTexture,
  24. InternalColorLut,
  25. AfterPostProcessColor,
  26. OverlayUITexture,
  27. DebugScreenColor,
  28. DebugScreenDepth
  29. }
  30. internal sealed partial class Renderer2D : ScriptableRenderer
  31. {
  32. RTHandle m_RenderGraphCameraColorHandle;
  33. RTHandle m_RenderGraphCameraDepthHandle;
  34. RTHandle m_RenderGraphBackbufferColorHandle;
  35. RTHandle m_RenderGraphBackbufferDepthHandle;
  36. RTHandle m_CameraSortingLayerHandle;
  37. DrawNormal2DPass m_NormalPass = new DrawNormal2DPass();
  38. DrawLight2DPass m_LightPass = new DrawLight2DPass();
  39. DrawShadow2DPass m_ShadowPass = new DrawShadow2DPass();
  40. DrawRenderer2DPass m_RendererPass = new DrawRenderer2DPass();
  41. LayerBatch[] m_LayerBatches;
  42. int m_BatchCount;
  43. bool ppcUpscaleRT = false;
  44. private struct ImportResourceSummary
  45. {
  46. internal RenderTargetInfo importInfo;
  47. internal RenderTargetInfo importInfoDepth;
  48. internal ImportResourceParams cameraColorParams;
  49. internal ImportResourceParams cameraDepthParams;
  50. internal ImportResourceParams backBufferColorParams;
  51. internal ImportResourceParams backBufferDepthParams;
  52. }
  53. ImportResourceSummary GetImportResourceSummary(RenderGraph renderGraph, UniversalCameraData cameraData)
  54. {
  55. ImportResourceSummary output = new ImportResourceSummary();
  56. bool clearColor = cameraData.renderType == CameraRenderType.Base;
  57. bool clearDepth = cameraData.renderType == CameraRenderType.Base || cameraData.clearDepth;
  58. bool clearBackbufferOnFirstUse = (cameraData.renderType == CameraRenderType.Base) && !m_CreateColorTexture;
  59. // if the camera background type is "uninitialized" clear using a yellow color, so users can clearly understand the underlying behaviour
  60. Color cameraBackgroundColor = (cameraData.camera.clearFlags == CameraClearFlags.Nothing) ? Color.yellow : cameraData.backgroundColor;
  61. if (IsSceneFilteringEnabled(cameraData.camera))
  62. {
  63. cameraBackgroundColor.a = 0;
  64. clearDepth = false;
  65. }
  66. // Certain debug modes (e.g. wireframe/overdraw modes) require that we override clear flags and clear everything.
  67. var debugHandler = cameraData.renderer.DebugHandler;
  68. if (debugHandler != null && debugHandler.IsActiveForCamera(cameraData.isPreviewCamera) && debugHandler.IsScreenClearNeeded)
  69. {
  70. clearColor = true;
  71. clearDepth = true;
  72. }
  73. output.cameraColorParams.clearOnFirstUse = clearColor;
  74. output.cameraColorParams.clearColor = cameraBackgroundColor;
  75. output.cameraColorParams.discardOnLastUse = false;
  76. output.cameraDepthParams.clearOnFirstUse = clearDepth;
  77. output.cameraDepthParams.clearColor = cameraBackgroundColor;
  78. output.cameraDepthParams.discardOnLastUse = false;
  79. output.backBufferColorParams.clearOnFirstUse = clearBackbufferOnFirstUse;
  80. output.backBufferColorParams.clearColor = cameraBackgroundColor;
  81. output.backBufferColorParams.discardOnLastUse = false;
  82. output.backBufferDepthParams.clearOnFirstUse = clearBackbufferOnFirstUse;
  83. output.backBufferDepthParams.clearColor = cameraBackgroundColor;
  84. output.backBufferDepthParams.discardOnLastUse = true;
  85. if (cameraData.targetTexture != null)
  86. {
  87. output.importInfo.width = cameraData.targetTexture.width;
  88. output.importInfo.height = cameraData.targetTexture.height;
  89. output.importInfo.volumeDepth = cameraData.targetTexture.volumeDepth;
  90. output.importInfo.msaaSamples = cameraData.targetTexture.antiAliasing;
  91. output.importInfo.format = cameraData.targetTexture.graphicsFormat;
  92. output.importInfoDepth = output.importInfo;
  93. output.importInfoDepth.format = cameraData.targetTexture.depthStencilFormat;
  94. // We let users know that a depth format is required for correct usage, but we fallback to the old default depth format behaviour to avoid regressions
  95. if (output.importInfoDepth.format == GraphicsFormat.None)
  96. {
  97. output.importInfoDepth.format = SystemInfo.GetGraphicsFormat(DefaultFormat.DepthStencil);
  98. Debug.LogWarning("In the render graph API, the output Render Texture must have a depth buffer. When you select a Render Texture in any camera's Output Texture property, the Depth Stencil Format property of the texture must be set to a value other than None.");
  99. }
  100. }
  101. else
  102. {
  103. bool msaaSamplesChangedThisFrame = false;
  104. #if !UNITY_EDITOR
  105. // for safety do this only for the NRP path, even though works also on non NRP, but would need extensive testing
  106. if (m_CreateColorTexture && renderGraph.nativeRenderPassesEnabled && Screen.msaaSamples > 1)
  107. {
  108. msaaSamplesChangedThisFrame = true;
  109. Screen.SetMSAASamples(1);
  110. }
  111. #endif
  112. int numSamples = Mathf.Max(Screen.msaaSamples, 1);
  113. // Handle edge cases regarding numSamples setup
  114. // On OSX player, the Screen API MSAA samples change request is only applied in the following frame,
  115. // as a workaround we keep the old MSAA sample count for the previous frame
  116. // this workaround can be removed once the Screen API issue (UUM-42825) is fixed
  117. // The editor always allocates the system rendertarget with a single msaa sample
  118. // See: ConfigureTargetTexture in PlayModeView.cs
  119. if (msaaSamplesChangedThisFrame && Application.platform == RuntimePlatform.OSXPlayer)
  120. numSamples = cameraData.cameraTargetDescriptor.msaaSamples;
  121. else if (Application.isEditor)
  122. numSamples = 1;
  123. //NOTE: Careful what you use here as many of the properties bake-in the camera rect so for example
  124. //cameraData.cameraTargetDescriptor.width is the width of the rectangle but not the actual render target
  125. //same with cameraData.camera.pixelWidth
  126. output.importInfo.width = Screen.width;
  127. output.importInfo.height = Screen.height;
  128. output.importInfo.volumeDepth = 1;
  129. output.importInfo.msaaSamples = numSamples;
  130. output.importInfo.format = UniversalRenderPipeline.MakeRenderTextureGraphicsFormat(cameraData.isHdrEnabled, cameraData.hdrColorBufferPrecision, Graphics.preserveFramebufferAlpha);
  131. output.importInfoDepth = output.importInfo;
  132. output.importInfoDepth.format = SystemInfo.GetGraphicsFormat(DefaultFormat.DepthStencil);
  133. }
  134. return output;
  135. }
  136. void InitializeLayerBatches()
  137. {
  138. Universal2DResourceData resourceData = frameData.Get<Universal2DResourceData>();
  139. m_LayerBatches = LayerUtility.CalculateBatches(m_Renderer2DData.lightCullResult, out m_BatchCount);
  140. // Initialize textures dependent on batch size
  141. if (resourceData.normalsTexture.Length != m_BatchCount)
  142. resourceData.normalsTexture = new TextureHandle[m_BatchCount];
  143. if (resourceData.lightTextures.Length != m_BatchCount)
  144. resourceData.lightTextures = new TextureHandle[m_BatchCount][];
  145. // Initialize light textures based on active blend styles to save on resources
  146. for (int i = 0; i < resourceData.lightTextures.Length; ++i)
  147. {
  148. if (resourceData.lightTextures[i] == null || resourceData.lightTextures[i].Length != m_LayerBatches[i].activeBlendStylesIndices.Length)
  149. resourceData.lightTextures[i] = new TextureHandle[m_LayerBatches[i].activeBlendStylesIndices.Length];
  150. }
  151. }
  152. void CreateResources(RenderGraph renderGraph)
  153. {
  154. Universal2DResourceData universal2DResourceData = frameData.Get<Universal2DResourceData>();
  155. CommonResourceData commonResourceData = frameData.Get<CommonResourceData>();
  156. UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
  157. ref var cameraTargetDescriptor = ref cameraData.cameraTargetDescriptor;
  158. var cameraTargetFilterMode = FilterMode.Bilinear;
  159. bool lastCameraInTheStack = cameraData.resolveFinalTarget;
  160. #if UNITY_EDITOR
  161. // The scene view camera cannot be uninitialized or skybox when using the 2D renderer.
  162. if (cameraData.cameraType == CameraType.SceneView)
  163. {
  164. cameraData.camera.clearFlags = CameraClearFlags.SolidColor;
  165. }
  166. #endif
  167. bool forceCreateColorTexture = false;
  168. // Pixel Perfect Camera doesn't support camera stacking.
  169. if (cameraData.renderType == CameraRenderType.Base && lastCameraInTheStack)
  170. {
  171. cameraData.camera.TryGetComponent<PixelPerfectCamera>(out var ppc);
  172. if (ppc != null && ppc.enabled)
  173. {
  174. if (ppc.offscreenRTSize != Vector2Int.zero)
  175. {
  176. forceCreateColorTexture = true;
  177. // Pixel Perfect Camera may request a different RT size than camera VP size.
  178. // In that case we need to modify cameraTargetDescriptor here so that all the passes would use the same size.
  179. cameraTargetDescriptor.width = ppc.offscreenRTSize.x;
  180. cameraTargetDescriptor.height = ppc.offscreenRTSize.y;
  181. }
  182. cameraTargetFilterMode = FilterMode.Point;
  183. ppcUpscaleRT = ppc.gridSnapping == PixelPerfectCamera.GridSnapping.UpscaleRenderTexture || ppc.requiresUpscalePass;
  184. if (ppc.requiresUpscalePass)
  185. {
  186. var upscaleDescriptor = cameraTargetDescriptor;
  187. upscaleDescriptor.width = ppc.refResolutionX * ppc.pixelRatio;
  188. upscaleDescriptor.height = ppc.refResolutionY * ppc.pixelRatio;
  189. upscaleDescriptor.depthBufferBits = 0;
  190. universal2DResourceData.upscaleTexture = UniversalRenderer.CreateRenderGraphTexture(renderGraph, upscaleDescriptor, "_UpscaleTexture", true, ppc.finalBlitFilterMode);
  191. }
  192. }
  193. }
  194. var renderTextureScale = m_Renderer2DData.lightRenderTextureScale;
  195. var width = (int)(cameraData.cameraTargetDescriptor.width * renderTextureScale);
  196. var height = (int)(cameraData.cameraTargetDescriptor.height * renderTextureScale);
  197. // Intermediate depth desc (size of renderTextureScale)
  198. {
  199. var depthDescriptor = new RenderTextureDescriptor(width, height);
  200. depthDescriptor.colorFormat = RenderTextureFormat.Depth;
  201. depthDescriptor.depthBufferBits = k_DepthBufferBits;
  202. depthDescriptor.width = width;
  203. depthDescriptor.height = height;
  204. universal2DResourceData.intermediateDepth = UniversalRenderer.CreateRenderGraphTexture(renderGraph, depthDescriptor, "DepthTexture", true);
  205. }
  206. // Normal and Light desc
  207. {
  208. var desc = new RenderTextureDescriptor(width, height);
  209. desc.graphicsFormat = RendererLighting.GetRenderTextureFormat();
  210. desc.autoGenerateMips = false;
  211. desc.depthBufferBits = 0;
  212. for (int i = 0; i < universal2DResourceData.normalsTexture.Length; ++i)
  213. universal2DResourceData.normalsTexture[i] = UniversalRenderer.CreateRenderGraphTexture(renderGraph, desc, "_NormalMap", true, RendererLighting.k_NormalClearColor);
  214. for (int i = 0; i < universal2DResourceData.lightTextures.Length; ++i)
  215. {
  216. for (var j = 0; j < m_LayerBatches[i].activeBlendStylesIndices.Length; ++j)
  217. {
  218. var index = m_LayerBatches[i].activeBlendStylesIndices[j];
  219. if (!Light2DManager.GetGlobalColor(m_LayerBatches[i].startLayerID, index, out var clearColor))
  220. clearColor = Color.black;
  221. universal2DResourceData.lightTextures[i][j] = UniversalRenderer.CreateRenderGraphTexture(renderGraph, desc, RendererLighting.k_ShapeLightTextureIDs[index], true, clearColor, FilterMode.Bilinear);
  222. }
  223. }
  224. }
  225. // Shadow desc
  226. {
  227. var desc = new RenderTextureDescriptor(width, height);
  228. desc.graphicsFormat = GraphicsFormat.B10G11R11_UFloatPack32;
  229. desc.autoGenerateMips = false;
  230. desc.depthBufferBits = 0;
  231. universal2DResourceData.shadowsTexture = UniversalRenderer.CreateRenderGraphTexture(renderGraph, desc, "_ShadowTex", false, FilterMode.Bilinear);
  232. }
  233. // Shadow depth desc
  234. {
  235. var desc = new RenderTextureDescriptor(width, height);
  236. desc.graphicsFormat = GraphicsFormat.None;
  237. desc.autoGenerateMips = false;
  238. desc.depthBufferBits = k_DepthBufferBits;
  239. universal2DResourceData.shadowsDepth = UniversalRenderer.CreateRenderGraphTexture(renderGraph, desc, "_ShadowDepth", false, FilterMode.Bilinear);
  240. }
  241. // Camera Sorting Layer desc
  242. if (m_Renderer2DData.useCameraSortingLayerTexture)
  243. {
  244. var descriptor = cameraTargetDescriptor;
  245. descriptor.msaaSamples = 1;
  246. CopyCameraSortingLayerPass.ConfigureDescriptor(m_Renderer2DData.cameraSortingLayerDownsamplingMethod, ref descriptor, out var filterMode);
  247. RenderingUtils.ReAllocateHandleIfNeeded(ref m_CameraSortingLayerHandle, descriptor, filterMode, TextureWrapMode.Clamp, name: CopyCameraSortingLayerPass.k_CameraSortingLayerTexture);
  248. universal2DResourceData.cameraSortingLayerTexture = renderGraph.ImportTexture(m_CameraSortingLayerHandle);
  249. }
  250. // now create the attachments
  251. if (cameraData.renderType == CameraRenderType.Base) // require intermediate textures
  252. {
  253. RenderPassInputSummary renderPassInputs = GetRenderPassInputs(cameraData);
  254. m_CreateColorTexture = renderPassInputs.requiresColorTexture;
  255. m_CreateDepthTexture = renderPassInputs.requiresDepthTexture;
  256. m_CreateColorTexture |= forceCreateColorTexture;
  257. // RTHandles do not support combining color and depth in the same texture so we create them separately
  258. m_CreateDepthTexture |= createColorTexture;
  259. // Camera Target Color
  260. if (createColorTexture)
  261. {
  262. cameraTargetDescriptor.useMipMap = false;
  263. cameraTargetDescriptor.autoGenerateMips = false;
  264. cameraTargetDescriptor.depthBufferBits = (int)DepthBits.None;
  265. RenderingUtils.ReAllocateHandleIfNeeded(ref m_RenderGraphCameraColorHandle, cameraTargetDescriptor, cameraTargetFilterMode, TextureWrapMode.Clamp, name: "_CameraTargetAttachment");
  266. commonResourceData.activeColorID = ActiveID.Camera;
  267. }
  268. else
  269. commonResourceData.activeColorID = ActiveID.BackBuffer;
  270. // Camera Target Depth
  271. if (createDepthTexture)
  272. {
  273. var depthDescriptor = cameraData.cameraTargetDescriptor;
  274. depthDescriptor.useMipMap = false;
  275. depthDescriptor.autoGenerateMips = false;
  276. depthDescriptor.bindMS = false;
  277. bool hasMSAA = depthDescriptor.msaaSamples > 1 && (SystemInfo.supportsMultisampledTextures != 0);
  278. bool resolveDepth = RenderingUtils.MultisampleDepthResolveSupported() && renderGraph.nativeRenderPassesEnabled;
  279. if (m_CopyDepthPass != null)
  280. m_CopyDepthPass.m_CopyResolvedDepth = resolveDepth;
  281. if (hasMSAA)
  282. {
  283. depthDescriptor.bindMS = !resolveDepth;
  284. }
  285. // binding MS surfaces is not supported by the GLES backend, and it won't be fixed after investigating
  286. if (IsGLDevice())
  287. depthDescriptor.bindMS = false;
  288. depthDescriptor.graphicsFormat = GraphicsFormat.None;
  289. depthDescriptor.depthStencilFormat = k_DepthStencilFormat;
  290. RenderingUtils.ReAllocateHandleIfNeeded(ref m_RenderGraphCameraDepthHandle, depthDescriptor, FilterMode.Point, TextureWrapMode.Clamp, name: "_CameraDepthAttachment");
  291. commonResourceData.activeDepthID = ActiveID.Camera;
  292. }
  293. else
  294. commonResourceData.activeDepthID = ActiveID.BackBuffer;
  295. }
  296. else // Overlay camera
  297. {
  298. cameraData.baseCamera.TryGetComponent<UniversalAdditionalCameraData>(out var baseCameraData);
  299. var baseRenderer = (Renderer2D)baseCameraData.scriptableRenderer;
  300. m_RenderGraphCameraColorHandle = baseRenderer.m_RenderGraphCameraColorHandle;
  301. m_RenderGraphCameraDepthHandle = baseRenderer.m_RenderGraphCameraDepthHandle;
  302. m_RenderGraphBackbufferColorHandle = baseRenderer.m_RenderGraphBackbufferColorHandle;
  303. m_RenderGraphBackbufferDepthHandle = baseRenderer.m_RenderGraphBackbufferDepthHandle;
  304. m_CreateColorTexture = baseRenderer.m_CreateColorTexture;
  305. m_CreateDepthTexture = baseRenderer.m_CreateDepthTexture;
  306. }
  307. ImportResourceSummary importSummary = GetImportResourceSummary(renderGraph, cameraData);
  308. if (m_CreateColorTexture)
  309. {
  310. importSummary.cameraColorParams.discardOnLastUse = lastCameraInTheStack;
  311. importSummary.cameraDepthParams.discardOnLastUse = lastCameraInTheStack;
  312. commonResourceData.cameraColor = renderGraph.ImportTexture(m_RenderGraphCameraColorHandle, importSummary.cameraColorParams);
  313. commonResourceData.cameraDepth = renderGraph.ImportTexture(m_RenderGraphCameraDepthHandle, importSummary.cameraDepthParams);
  314. }
  315. RenderTargetIdentifier targetColorId = cameraData.targetTexture != null ? new RenderTargetIdentifier(cameraData.targetTexture) : BuiltinRenderTextureType.CameraTarget;
  316. RenderTargetIdentifier targetDepthId = cameraData.targetTexture != null ? new RenderTargetIdentifier(cameraData.targetTexture) : BuiltinRenderTextureType.Depth;
  317. if (m_RenderGraphBackbufferColorHandle == null)
  318. {
  319. m_RenderGraphBackbufferColorHandle = RTHandles.Alloc(targetColorId, "Backbuffer color");
  320. }
  321. else if (m_RenderGraphBackbufferColorHandle.nameID != targetColorId)
  322. {
  323. RTHandleStaticHelpers.SetRTHandleUserManagedWrapper(ref m_RenderGraphBackbufferColorHandle, targetColorId);
  324. }
  325. if (m_RenderGraphBackbufferDepthHandle == null)
  326. {
  327. m_RenderGraphBackbufferDepthHandle = RTHandles.Alloc(targetDepthId, "Backbuffer depth");
  328. }
  329. else if (m_RenderGraphBackbufferDepthHandle.nameID != targetDepthId)
  330. {
  331. RTHandleStaticHelpers.SetRTHandleUserManagedWrapper(ref m_RenderGraphBackbufferDepthHandle, targetDepthId);
  332. }
  333. commonResourceData.backBufferColor = renderGraph.ImportTexture(m_RenderGraphBackbufferColorHandle, importSummary.importInfo, importSummary.backBufferColorParams);
  334. commonResourceData.backBufferDepth = renderGraph.ImportTexture(m_RenderGraphBackbufferDepthHandle, importSummary.importInfoDepth, importSummary.backBufferDepthParams);
  335. var postProcessDesc = PostProcessPass.GetCompatibleDescriptor(cameraTargetDescriptor, cameraTargetDescriptor.width, cameraTargetDescriptor.height, cameraTargetDescriptor.graphicsFormat, DepthBits.None);
  336. commonResourceData.afterPostProcessColor = UniversalRenderer.CreateRenderGraphTexture(renderGraph, postProcessDesc, "_AfterPostProcessTexture", true);
  337. if (RequiresDepthCopyPass(cameraData))
  338. CreateCameraDepthCopyTexture(renderGraph, cameraTargetDescriptor);
  339. }
  340. bool RequiresDepthCopyPass(UniversalCameraData cameraData)
  341. {
  342. var renderPassInputs = GetRenderPassInputs(cameraData);
  343. bool cameraHasPostProcessingWithDepth = cameraData.postProcessEnabled && m_PostProcessPasses.isCreated && cameraData.postProcessingRequiresDepthTexture;
  344. bool requiresDepthCopyPass = (cameraHasPostProcessingWithDepth || renderPassInputs.requiresDepthTexture) && m_CreateDepthTexture;
  345. return requiresDepthCopyPass;
  346. }
  347. void CreateCameraDepthCopyTexture(RenderGraph renderGraph, RenderTextureDescriptor descriptor)
  348. {
  349. CommonResourceData resourceData = frameData.Get<CommonResourceData>();
  350. var depthDescriptor = descriptor;
  351. depthDescriptor.msaaSamples = 1;// Depth-Only pass don't use MSAA
  352. depthDescriptor.graphicsFormat = GraphicsFormat.R32_SFloat;
  353. depthDescriptor.depthStencilFormat = GraphicsFormat.None;
  354. depthDescriptor.depthBufferBits = 0;
  355. resourceData.cameraDepthTexture = UniversalRenderer.CreateRenderGraphTexture(renderGraph, depthDescriptor, "_CameraDepthTexture", true);
  356. }
  357. public override void OnBeginRenderGraphFrame()
  358. {
  359. Universal2DResourceData universal2DResourceData = frameData.Create<Universal2DResourceData>();
  360. CommonResourceData commonResourceData = frameData.GetOrCreate<CommonResourceData>();
  361. universal2DResourceData.InitFrame();
  362. commonResourceData.InitFrame();
  363. }
  364. internal void RecordCustomRenderGraphPasses(RenderGraph renderGraph, RenderPassEvent2D activeRPEvent)
  365. {
  366. foreach (ScriptableRenderPass pass in activeRenderPassQueue)
  367. {
  368. pass.GetInjectionPoint2D(out RenderPassEvent2D rpEvent, out int rpLayer);
  369. if (rpEvent == activeRPEvent)
  370. pass.RecordRenderGraph(renderGraph, frameData);
  371. }
  372. }
  373. internal override void OnRecordRenderGraph(RenderGraph renderGraph, ScriptableRenderContext context)
  374. {
  375. CommonResourceData commonResourceData = frameData.GetOrCreate<CommonResourceData>();
  376. InitializeLayerBatches();
  377. CreateResources(renderGraph);
  378. SetupRenderGraphCameraProperties(renderGraph, commonResourceData.isActiveTargetBackBuffer);
  379. #if VISUAL_EFFECT_GRAPH_0_0_1_OR_NEWER
  380. ProcessVFXCameraCommand(renderGraph);
  381. #endif
  382. OnBeforeRendering(renderGraph);
  383. RecordCustomRenderGraphPasses(renderGraph, RenderPassEvent2D.BeforeRendering);
  384. OnMainRendering(renderGraph);
  385. RecordCustomRenderGraphPasses(renderGraph, RenderPassEvent2D.BeforeRenderingPostProcessing);
  386. OnAfterRendering(renderGraph);
  387. }
  388. public override void OnEndRenderGraphFrame()
  389. {
  390. Universal2DResourceData universal2DResourceData = frameData.Get<Universal2DResourceData>();
  391. CommonResourceData commonResourceData = frameData.Get<CommonResourceData>();
  392. universal2DResourceData.EndFrame();
  393. commonResourceData.EndFrame();
  394. }
  395. internal override void OnFinishRenderGraphRendering(CommandBuffer cmd)
  396. {
  397. m_CopyDepthPass?.OnCameraCleanup(cmd);
  398. }
  399. private void OnBeforeRendering(RenderGraph renderGraph)
  400. {
  401. UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
  402. m_LightPass.Setup(renderGraph, ref m_Renderer2DData);
  403. // Before rendering the lights cache some values that are expensive to get/calculate
  404. var culledLights = m_Renderer2DData.lightCullResult.visibleLights;
  405. for (var i = 0; i < culledLights.Count; i++)
  406. {
  407. culledLights[i].CacheValues();
  408. }
  409. ShadowCasterGroup2DManager.CacheValues();
  410. ShadowRendering.CallOnBeforeRender(cameraData.camera, m_Renderer2DData.lightCullResult);
  411. RendererLighting.lightBatch.Reset();
  412. }
  413. private void OnMainRendering(RenderGraph renderGraph)
  414. {
  415. Universal2DResourceData universal2DResourceData = frameData.Get<Universal2DResourceData>();
  416. CommonResourceData commonResourceData = frameData.Get<CommonResourceData>();
  417. UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
  418. // Color Grading LUT
  419. bool requiredColorGradingLutPass = cameraData.postProcessEnabled && m_PostProcessPasses.isCreated;
  420. if (requiredColorGradingLutPass)
  421. {
  422. TextureHandle internalColorLut;
  423. m_PostProcessPasses.colorGradingLutPass.Render(renderGraph, frameData, out internalColorLut);
  424. commonResourceData.internalColorLut = internalColorLut;
  425. }
  426. var cameraSortingLayerBoundsIndex = Render2DLightingPass.GetCameraSortingLayerBoundsIndex(m_Renderer2DData);
  427. // Main render passes
  428. // Normal Pass
  429. for (var i = 0; i < m_BatchCount; i++)
  430. m_NormalPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches[i], i);
  431. // Shadow Pass (TODO: Optimize RT swapping between shadow and light textures)
  432. for (var i = 0; i < m_BatchCount; i++)
  433. m_ShadowPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches[i], i);
  434. // Light Pass
  435. for (var i = 0; i < m_BatchCount; i++)
  436. m_LightPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches[i], i);
  437. // Default Render Pass
  438. for (var i = 0; i < m_BatchCount; i++)
  439. {
  440. if (!renderGraph.nativeRenderPassesEnabled && i == 0)
  441. {
  442. RTClearFlags clearFlags = (RTClearFlags)GetCameraClearFlag(cameraData);
  443. if (clearFlags != RTClearFlags.None)
  444. ClearTargetsPass.Render(renderGraph, commonResourceData.activeColorTexture, commonResourceData.activeDepthTexture, clearFlags, cameraData.backgroundColor);
  445. }
  446. ref var layerBatch = ref m_LayerBatches[i];
  447. LayerUtility.GetFilterSettings(m_Renderer2DData, ref m_LayerBatches[i], cameraSortingLayerBoundsIndex, out var filterSettings);
  448. m_RendererPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches, i, ref filterSettings);
  449. // Shadow Volumetric Pass
  450. m_ShadowPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches[i], i, true);
  451. // Light Volumetric Pass
  452. m_LightPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches[i], i, true);
  453. // Camera Sorting Layer Pass
  454. if (m_Renderer2DData.useCameraSortingLayerTexture)
  455. {
  456. // Split Render Pass if CameraSortingLayer is in the middle of a batch
  457. if (cameraSortingLayerBoundsIndex >= layerBatch.layerRange.lowerBound && cameraSortingLayerBoundsIndex < layerBatch.layerRange.upperBound)
  458. {
  459. m_CopyCameraSortingLayerPass.Render(renderGraph, commonResourceData.activeColorTexture, universal2DResourceData.cameraSortingLayerTexture);
  460. filterSettings.sortingLayerRange = new SortingLayerRange((short)(cameraSortingLayerBoundsIndex + 1), layerBatch.layerRange.upperBound);
  461. m_RendererPass.Render(renderGraph, frameData, m_Renderer2DData, ref m_LayerBatches, i, ref filterSettings);
  462. }
  463. else if (cameraSortingLayerBoundsIndex == layerBatch.layerRange.upperBound)
  464. {
  465. m_CopyCameraSortingLayerPass.Render(renderGraph, commonResourceData.activeColorTexture, universal2DResourceData.cameraSortingLayerTexture);
  466. }
  467. }
  468. }
  469. if (RequiresDepthCopyPass(cameraData))
  470. m_CopyDepthPass?.Render(renderGraph, frameData, commonResourceData.cameraDepthTexture, commonResourceData.activeDepthTexture, true);
  471. bool shouldRenderUI = cameraData.rendersOverlayUI;
  472. bool outputToHDR = cameraData.isHDROutputActive;
  473. if (shouldRenderUI && outputToHDR)
  474. {
  475. TextureHandle overlayUI;
  476. m_DrawOffscreenUIPass.RenderOffscreen(renderGraph, frameData, k_DepthStencilFormat, out overlayUI);
  477. commonResourceData.overlayUITexture = overlayUI;
  478. }
  479. }
  480. private void OnAfterRendering(RenderGraph renderGraph)
  481. {
  482. Universal2DResourceData universal2DResourceData = frameData.Get<Universal2DResourceData>();
  483. CommonResourceData commonResourceData = frameData.Get<CommonResourceData>();
  484. UniversalRenderingData renderingData = frameData.Get<UniversalRenderingData>();
  485. UniversalCameraData cameraData = frameData.Get<UniversalCameraData>();
  486. UniversalPostProcessingData postProcessingData = frameData.Get<UniversalPostProcessingData>();
  487. bool drawGizmos = UniversalRenderPipelineDebugDisplaySettings.Instance.renderingSettings.sceneOverrideMode == DebugSceneOverrideMode.None;
  488. if (drawGizmos)
  489. DrawRenderGraphGizmos(renderGraph, frameData, commonResourceData.activeColorTexture, commonResourceData.activeDepthTexture, GizmoSubset.PreImageEffects);
  490. DebugHandler debugHandler = ScriptableRenderPass.GetActiveDebugHandler(cameraData);
  491. bool resolveToDebugScreen = debugHandler != null && debugHandler.WriteToDebugScreenTexture(cameraData.resolveFinalTarget);
  492. // Allocate debug screen texture if the debug mode needs it.
  493. if (resolveToDebugScreen)
  494. {
  495. RenderTextureDescriptor colorDesc = cameraData.cameraTargetDescriptor;
  496. DebugHandler.ConfigureColorDescriptorForDebugScreen(ref colorDesc, cameraData.pixelWidth, cameraData.pixelHeight);
  497. commonResourceData.debugScreenColor = UniversalRenderer.CreateRenderGraphTexture(renderGraph, colorDesc, "_DebugScreenColor", false);
  498. RenderTextureDescriptor depthDesc = cameraData.cameraTargetDescriptor;
  499. DebugHandler.ConfigureDepthDescriptorForDebugScreen(ref depthDesc, k_DepthStencilFormat, cameraData.pixelWidth, cameraData.pixelHeight);
  500. commonResourceData.debugScreenDepth = UniversalRenderer.CreateRenderGraphTexture(renderGraph, depthDesc, "_DebugScreenDepth", false);
  501. }
  502. bool applyPostProcessing = postProcessingData.isEnabled && m_PostProcessPasses.isCreated;
  503. cameraData.camera.TryGetComponent<PixelPerfectCamera>(out var ppc);
  504. bool isPixelPerfectCameraEnabled = ppc != null && ppc.enabled && ppc.cropFrame != PixelPerfectCamera.CropFrame.None;
  505. bool requirePixelPerfectUpscale = isPixelPerfectCameraEnabled && ppc.requiresUpscalePass;
  506. // When using Upscale Render Texture on a Pixel Perfect Camera, we want all post-processing effects done with a low-res RT,
  507. // and only upscale the low-res RT to fullscreen when blitting it to camera target. Also, final post processing pass is not run in this case,
  508. // so FXAA is not supported (you don't want to apply FXAA when everything is intentionally pixelated).
  509. bool requireFinalPostProcessPass = cameraData.resolveFinalTarget && !ppcUpscaleRT && applyPostProcessing && cameraData.antialiasing == AntialiasingMode.FastApproximateAntialiasing;
  510. bool hasPassesAfterPostProcessing = activeRenderPassQueue.Find(x => x.renderPassEvent == RenderPassEvent.AfterRenderingPostProcessing) != null;
  511. bool needsColorEncoding = DebugHandler == null || !DebugHandler.HDRDebugViewIsActive(cameraData.resolveFinalTarget);
  512. var finalColorHandle = commonResourceData.activeColorTexture;
  513. if (applyPostProcessing)
  514. {
  515. postProcessPass.RenderPostProcessingRenderGraph(
  516. renderGraph,
  517. frameData,
  518. commonResourceData.activeColorTexture,
  519. commonResourceData.internalColorLut,
  520. commonResourceData.overlayUITexture,
  521. commonResourceData.afterPostProcessColor,
  522. requireFinalPostProcessPass,
  523. resolveToDebugScreen,
  524. needsColorEncoding);
  525. finalColorHandle = commonResourceData.afterPostProcessColor;
  526. }
  527. RecordCustomRenderGraphPasses(renderGraph, RenderPassEvent2D.AfterRenderingPostProcessing);
  528. // Do PixelPerfect upscaling when using the Stretch Fill option
  529. if (requirePixelPerfectUpscale)
  530. {
  531. m_UpscalePass.Render(renderGraph, cameraData.camera, in finalColorHandle, universal2DResourceData.upscaleTexture);
  532. finalColorHandle = universal2DResourceData.upscaleTexture;
  533. }
  534. // We need to switch the "final" blit target to debugScreenColor if HDR debug views are enabled.
  535. var finalBlitTarget = resolveToDebugScreen ? commonResourceData.debugScreenColor : commonResourceData.backBufferColor;
  536. var finalDepthHandle = resolveToDebugScreen ? commonResourceData.debugScreenDepth : commonResourceData.backBufferDepth;
  537. if (createColorTexture)
  538. {
  539. if (requireFinalPostProcessPass)
  540. postProcessPass.RenderFinalPassRenderGraph(renderGraph, frameData, in finalColorHandle, commonResourceData.overlayUITexture, in finalBlitTarget, needsColorEncoding);
  541. else
  542. m_FinalBlitPass.Render(renderGraph, frameData, cameraData, finalColorHandle, finalBlitTarget, commonResourceData.overlayUITexture);
  543. finalColorHandle = finalBlitTarget;
  544. }
  545. // We can explicitly render the overlay UI from URP when HDR output is not enabled.
  546. // SupportedRenderingFeatures.active.rendersUIOverlay should also be set to true.
  547. bool shouldRenderUI = cameraData.rendersOverlayUI;
  548. bool outputToHDR = cameraData.isHDROutputActive;
  549. if (shouldRenderUI && !outputToHDR)
  550. m_DrawOverlayUIPass.RenderOverlay(renderGraph, frameData, in finalColorHandle, in finalDepthHandle);
  551. // If HDR debug views are enabled, DebugHandler will perform the blit from debugScreenColor (== finalColorHandle) to backBufferColor.
  552. DebugHandler?.Setup(renderGraph, cameraData.isPreviewCamera);
  553. DebugHandler?.Render(renderGraph, cameraData, finalColorHandle, commonResourceData.overlayUITexture, commonResourceData.backBufferColor);
  554. if (drawGizmos)
  555. DrawRenderGraphGizmos(renderGraph, frameData, commonResourceData.backBufferColor, commonResourceData.activeDepthTexture, GizmoSubset.PostImageEffects);
  556. }
  557. private void CleanupRenderGraphResources()
  558. {
  559. m_RenderGraphCameraColorHandle?.Release();
  560. m_RenderGraphCameraDepthHandle?.Release();
  561. m_RenderGraphBackbufferColorHandle?.Release();
  562. m_RenderGraphBackbufferDepthHandle?.Release();
  563. m_CameraSortingLayerHandle?.Release();
  564. m_LightPass.Dispose();
  565. }
  566. }
  567. }