自由学习记录(83)
[System.Serializable]
把一个内部 Settings
类标记为可被 Unity 序列化,这样它会在 Inspector 里以可展开的块出现
using System;
using UnityEngine;public class Player : MonoBehaviour
{//Create a custom struct and apply [Serializable] attribute to it[Serializable]public struct PlayerStats{public int movementSpeed;public int hitPoints;public bool hasHealthPotion;}//Make the private field of our PlayerStats struct visible in the Inspector//by applying [SerializeField] attribute to it[SerializeField]private PlayerStats stats;
}
https://docs.unity3d.com/2022.1/Documentation/ScriptReference/Serializable.html
自定义 ScriptableRendererFeature 示例里常用的模式
Feature 脚本里定义一个 Settings
容器,里面放材质、注入时机等配置
在 AddRenderPasses
/Execute
里读取这些配置执行渲染
序列化满足条件的字段(非 static/const/readonly
,类型可序列化等),Material
这类 UnityEngine.Object
也会被序列化为资源引用。
Enum RenderPassEvent
Controls when the render pass executes.
Syntax
public enum RenderPassEvent
Fields
Name | Description |
---|---|
AfterRendering | |
AfterRenderingOpaques | |
AfterRenderingPostProcessing | |
AfterRenderingPrePasses | |
AfterRenderingShadows | |
AfterRenderingSkybox | |
AfterRenderingTransparents | |
BeforeRendering | |
BeforeRenderingOpaques | |
BeforeRenderingPostProcessing | |
BeforeRenderingPrepasses | |
BeforeRenderingShadows | |
BeforeRenderingSkybox | |
BeforeRenderingTransparents |
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@7.2/api/UnityEngine.Rendering.Universal.RenderPassEvent.html
Syntax
public abstract class ScriptableRenderPass : IRenderGraphRecorder
Remarks
To implement your own rendering pass you need to take the following steps:
- Create a new Subclass from ScriptableRenderPass that implements the rendering logic.
- Create an instance of your subclass and set up the relevant parameters such as
ScriptableRenderPass.renderPassEvent
in the constructor or initialization code. - Ensure your pass instance gets picked up by URP, this can be done through a
ScriptableRendererFeature
or by callingScriptableRenderer.EnqueuePass
from an event callback likeRenderPipelineManager.beginCameraRendering
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.2/api/UnityEngine.Rendering.Universal.ScriptableRenderPass.html#constructors
ScriptableRenderPass Properties
clearColor
The color value to use when clearing.
Declaration
public Color clearColor { get; }
clearFlag
The flag to use when clearing.
Declaration
public ClearFlag clearFlag { get; }
colorAttachmentHandle
The main color attachment handle.
Declaration
public RTHandle colorAttachmentHandle { get; }
colorAttachmentHandles
List for the g-buffer attachment handles.
Declaration
public RTHandle[] colorAttachmentHandles { get; }
colorStoreActions
The store actions for Color.
Declaration
public RenderBufferStoreAction[] colorStoreActions { get; }
depthAttachmentHandle
The depth attachment handle.
Declaration
public RTHandle depthAttachmentHandle { get; }
depthStoreAction
The store actions for Depth.
Declaration
public RenderBufferStoreAction depthStoreAction { get; }
input
The input requirements for the ScriptableRenderPass
, which has been set using ConfigureInput
Declaration
public ScriptableRenderPassInput input { get; }
passName
The name of the pass that will show up in profiler and other tools. This will be indentical to the name of profilingSampler
. profilingSampler
is set to null in the release build (non-development) so this passName
property is the safe way to access the name and use it consistently. This will always return a valid string.
Declaration
protected string passName { get; }
profilingSampler
A ProfilingSampler for the entire render pass. Used as a profiling name by ScriptableRenderer
when executing the pass. The default is named as the class type of the sub-class. Set base.profilingSampler
from the sub-class constructor to set a different profiling name for a custom ScriptableRenderPass This returns null in release build (non-development).
.
Declaration
protected ProfilingSampler profilingSampler { get; set; }
renderPassEvent
The event when the render pass executes.
Declaration
public RenderPassEvent renderPassEvent { get; set; }
requiresIntermediateTexture
Setting this property to true forces rendering of all passes in the URP frame via an intermediate texture. Use this option for passes that do not support rendering directly to the backbuffer or that require sampling the active color target. Using this option might have a significant performance impact on untethered VR platforms.
Declaration
public bool requiresIntermediateTexture { get; set;
ScriptableRenderPass Methods
ConfigureInput(ScriptableRenderPassInput)
Configures Input Requirements for this render pass. This method should be called inside ScriptableRendererFeature.AddRenderPasses
.
Declaration
public void ConfigureInput(ScriptableRenderPassInput passInput)
Parameters
Type | Name | Description |
---|---|---|
ScriptableRenderPassInput | passInput | ScriptableRenderPassInput containing information about what requirements the pass needs. |
See Also
AddRenderPasses(ScriptableRenderer, ref RenderingData)
CreateDrawingSettings(List<ShaderTagId>, ref RenderingData, SortingCriteria)
Creates DrawingSettings
based on current rendering state.
Declaration
public DrawingSettings CreateDrawingSettings(List<ShaderTagId> shaderTagIdList, ref RenderingData renderingData, SortingCriteria sortingCriteria)
Parameters
Type | Name | Description |
---|---|---|
List<ShaderTagId> | shaderTagIdList | List of shader pass tag to render. |
RenderingData | renderingData | Current rendering state. |
SortingCriteria | sortingCriteria | Criteria to sort objects being rendered. |
Returns
Type | Description |
---|---|
DrawingSettings | Returns the draw settings created. |
See Also
DrawingSettings
CreateDrawingSettings(List<ShaderTagId>, UniversalRenderingData, UniversalCameraData, UniversalLightData, SortingCriteria)
Creates DrawingSettings
based on current rendering state.
Declaration
public DrawingSettings CreateDrawingSettings(List<ShaderTagId> shaderTagIdList, UniversalRenderingData renderingData, UniversalCameraData cameraData, UniversalLightData lightData, SortingCriteria sortingCriteria)
Parameters
Type | Name | Description |
---|---|---|
List<ShaderTagId> | shaderTagIdList | List of shader pass tag to render. |
UniversalRenderingData | renderingData | Current rendering state. |
UniversalCameraData | cameraData | Current camera state. |
UniversalLightData | lightData | Current light state. |
SortingCriteria | sortingCriteria | Criteria to sort objects being rendered. |
Returns
Type | Description |
---|---|
DrawingSettings | Returns the draw settings created. |
CreateDrawingSettings(ShaderTagId, ref RenderingData, SortingCriteria)
Creates DrawingSettings
based on current the rendering state.
Declaration
public DrawingSettings CreateDrawingSettings(ShaderTagId shaderTagId, ref RenderingData renderingData, SortingCriteria sortingCriteria)
Parameters
Type | Name | Description |
---|---|---|
ShaderTagId | shaderTagId | Shader pass tag to render. |
RenderingData | renderingData | Current rendering state. |
SortingCriteria | sortingCriteria | Criteria to sort objects being rendered. |
Returns
Type | Description |
---|---|
DrawingSettings | Returns the draw settings created. |
CreateDrawingSettings(ShaderTagId, UniversalRenderingData, UniversalCameraData, UniversalLightData, SortingCriteria)
Creates DrawingSettings
based on current the rendering state.
Declaration
public DrawingSettings CreateDrawingSettings(ShaderTagId shaderTagId, UniversalRenderingData renderingData, UniversalCameraData cameraData, UniversalLightData lightData, SortingCriteria sortingCriteria)
Parameters
Type | Name | Description |
---|---|---|
ShaderTagId | shaderTagId | Shader pass tag to render. |
UniversalRenderingData | renderingData | Current rendering state. |
UniversalCameraData | cameraData | Current camera state. |
UniversalLightData | lightData | Current light state. |
SortingCriteria | sortingCriteria | Criteria to sort objects being rendered. |
Returns
Type | Description |
---|---|
DrawingSettings | Returns the draw settings created. |
OnCameraCleanup(CommandBuffer)
Called upon finish rendering a camera. You can use this callback to release any resources created by this render pass that need to be cleanup once camera has finished rendering. This method should be called for all cameras in a camera stack.
Declaration
public virtual void OnCameraCleanup(CommandBuffer cmd)
Parameters
Type | Name | Description |
---|---|---|
CommandBuffer | cmd | Use this CommandBuffer to cleanup any generated data |
RecordRenderGraph(RenderGraph, ContextContainer)
Declaration
public virtual void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
Parameters
Type | Name | Description |
---|---|---|
RenderGraph | renderGraph | |
ContextContainer | frameData |
Operators
operator >(ScriptableRenderPass, ScriptableRenderPass)
Compares two instances of ScriptableRenderPass
by their RenderPassEvent
and returns if lhs
is executed after rhs
.
Declaration
public static bool operator >(ScriptableRenderPass lhs, ScriptableRenderPass rhs)
Parameters
Type | Name | Description |
---|---|---|
ScriptableRenderPass | lhs | |
ScriptableRenderPass | rhs |
operator <(ScriptableRenderPass, ScriptableRenderPass)
Compares two instances of ScriptableRenderPass
by their RenderPassEvent
and returns if lhs
is executed before rhs
.
Declaration
public static bool operator <(ScriptableRenderPass lhs, ScriptableRenderPass rhs)
Parameters
Type | Name | Description |
---|---|---|
ScriptableRenderPass | lhs | |
ScriptableRenderPass | rhs |
xxxxx
Renderer Feature 的设置里直接拖 Material
很常见,方便你在不同 Renderer 资产里用不同材质/参数。官方示例也是这么做的(把材质等参数收进 Settings)
RenderTextureDescriptor
RenderingData---. cameraData. cameraTargetDescriptor
相机当前“目标贴图”的参数模板(尺寸、MSAA、格式、XR 设置等),URP 用它来创建各种中间纹理。拿它来创建你的临时 RT,能保证和相机一模一样,不会尺寸/格式错配
RenderTextureDescriptor---.depthBufferBits = 0
把 深度缓冲关掉(只要颜色)。全屏后处理通常不需要给临时 RT 分配深度,关掉能省内存和带宽;如果你要在这张临时 RT 里“再画几何体”,才需要 16/24/32 位深度。
OnCameraSetup(...):渲染器在绘制相机前调用。专门用来配置渲染目标/清屏,或创建临时贴图
RenderingData
里带着当前相机、管线与平台的组合设置(如 cameraData.cameraTargetDescriptor
)。
Struct that flattens several rendering settings used to render a camera stack. URP builds the RenderingData
settings from several places, including the pipeline asset, camera and light settings. The settings also might vary on different platforms and depending on if Adaptive Performance is used.
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal%4014.0/api/UnityEngine.Rendering.Universal.RenderingData.html
RenderingData
Fields
cameraData
Holds several rendering settings related to camera. CameraData
Declaration
public CameraData cameraData
Field Value
Type | Description |
---|---|
CameraData |
cullResults
Returns culling results that exposes handles to visible objects, lights and probes. You can use this to draw objects with ScriptableRenderContext.DrawRenderers
CullingResults ScriptableRenderContext
Declaration
public CullingResults cullResults
Field Value
Type | Description |
---|---|
CullingResults |
lightData
Holds several rendering settings related to lights. LightData
Declaration
public LightData lightData
Field Value
Type | Description |
---|---|
LightData |
perObjectData
Holds per-object data that are requested when drawing PerObjectData
Declaration
public PerObjectData perObjectData
Field Value
Type | Description |
---|---|
PerObjectData |
postProcessingData
Holds several rendering settings and resources related to the integrated post-processing stack. PostProcessData
Declaration
public PostProcessingData postProcessingData
Field Value
Type | Description |
---|---|
PostProcessingData |
postProcessingEnabled
True if post-processing effect is enabled while rendering the camera stack.
Declaration
public bool postProcessingEnabled
Field Value
Type | Description |
---|---|
bool |
shadowData
Holds several rendering settings related to shadows. ShadowData
Declaration
public ShadowData shadowData
Field Value
Type | Description |
---|---|
ShadowData |
supportsDynamicBatching
True if the pipeline supports dynamic batching. This settings doesn't apply when drawing shadow casters. Dynamic batching is always disabled when drawing shadow casters.
Declaration
public bool supportsDynamicBatching
Field Value
Type | Description |
---|---|
bool |
-
池里拿一个
CommandBuffer
; -
先把 相机颜色(
source
)Blit 到一张临时 RT(tempTexture
),并套你的后处理材质; -
再把临时 RT Blit 回 相机颜色;
-
执行命令并释放
CommandBuffer
(临时 RT 的创建/释放通常放在OnCameraSetup/FrameCleanup
)。
添加进渲染流程,feature是驱动器,这里就是
Renderer Feature是在扩展 URP
给 URP 的某个 Renderer 挂自定义“渲染步骤”,它的核心是把一个或多个 ScriptableRenderPass 插入到 URP的时间轴(RenderPassEvent)中。
在 Execute
里 context.DrawRenderers(...)
(画一批物体),也可做 Blit 全屏处理,或先把目标切到自建 RT 再合成。URP 自己内部的“画不透明/画透明/拷贝深度/阴影”等,也都是一堆 ScriptableRenderPass。
ShaderLab 里的 Pass{}
。URP通过LightMode 标签决定在某个渲染阶段调用哪一个 Pass(例如 UniversalForward
/ UniversalForwardOnly
/ ShadowCaster
/ DepthNormalsOnly
/ UniversalGBuffer
等)。一个 Shader Pass 对应一次 draw call 的“这套光栅/深度/混合+像素规则”。
一个 Shader Pass 对应一次 draw call 的“这套光栅/深度/混合+像素规则”
管线 Pass(ScriptableRenderPass)决定“何时/画谁/画到哪”;Shader Pass 决定“怎么画”。
让你在某个时机(如不透明后/透明前)筛一批对象(按 Layer/Queue/ShaderTag),可改材质/模板/深度写入再画一遍,用于描边、透视显示、遮罩写入等。你也能自己写一个更灵活的 Pass 来 DrawRenderers
到自定义的 RenderTexture,再在后面合成。
替代 GrabPass 的官方手段是 Opaque Texture:URP 可生成 _CameraOpaqueTexture
,它是“刚画完不透明物体时的画面快照”,常用来做折射/热扰动等。注意,它不包含透明 & 后处理;若要“透明之后”的颜色,得自己在合适注入点做拷贝/渲染到 RT。
自定义阶段的“抓取”:在特定 RenderPassEvent(例如 AfterOpaque/AfterTransparents/BeforePostProcessing…)里把 camera color Blit 到你自己的 RT,或者直接把目标切到你的 RT 再 DrawRenderers
,之后再合成回屏幕。这就是“抓中间结果”的 SRP 做法。官方“自定义 Renderer Feature/Pass(如模糊)”示例就是这个套路。
为什么 URP 里“多 Pass 的自由度”感觉受限?
-
因为 URP 约定“哪些 LightMode 会被用在什么阶段”,很多内置管线里常见的 LightMode(如
ForwardAdd
、Always
)URP 不支持;再加上 URP 的前向路径倾向单 Pass 完成光照,所以你不会再像以前那样“堆很多 Shader Pass 来实现不同阶段”。这不是不能扩展,而是把“阶段控制”上收到了管线层(ScriptableRenderPass)
Render Objects Renderer Feature Properties
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal%4013.1/manual/renderer-features/renderer-feature-render-objects.html
How to use the Render Objects Renderer Feature
The Render Objects Renderer Feature contains the following properties.
Property | Description |
---|---|
Name | Use this field to edit the name of the feature. |
Event | The event in the URP queue when Unity executes this Renderer Feature. |
Filters | Settings that let you configure which objects this Renderer Feature renders. |
Queue | Select whether the feature renders opaque or transparent objects. |
Layer Mask | The Renderer Feature renders objects from layers you select in this property. |
Pass Names | If a Pass in a shader has the LightMode Pass Tag, this Renderer Feature processes only the shaders where the value of the LightMode Pass Tag equals one of the values in the Pass Names property. |
Overrides | Settings in this section let you configure overrides for certain properties when rendering with this Renderer Feature. |
Override Mode | Specify the material override mode. |
Material | (Override Mode is set to Material) When rendering an object, Unity replaces the Material assigned to it with this Material. This will override all material properties with this material |
Shader | (Override Mode is set to Shader) When rendering an object, Unity replaces the material assigned to it with this shader. This maintains all material properties and allows the override shader to access these properties. This is currently not SRPBatcher compatible and less performant. |
Depth | Selecting this option lets you specify how this Renderer Feature affects or uses the Depth buffer. This option contains the following items: Write Depth: this option defines whether the Renderer Feature updates the Depth buffer when rendering objects. Depth Test: the condition which determines when this Renderer Feature renders pixels of a given object. |
Stencil | With this check box selected, the Renderer processes the Stencil buffer values. For more information on how Unity works with the Stencil buffer, see ShaderLab: Stencil. |
Camera | Selecting this option lets you override the following Camera properties: Field of View: when rendering objects, the Renderer Feature uses this Field of View instead of the value specified on the Camera. Position Offset: when rendering objects, the Renderer Feature moves them by this offset. Restore: with this option selected, the Renderer Feature restores the original Camera matrices after executing the render passes in this Renderer Feature. |
Depth Stencil Format | Set the GraphicsFormat of the depth/stencil buffer of the Render Texture. If you select None, Unity doesn’t allocate a depth/stencil buffer for this Render Texture. The stencil buffer is a general purpose buffer that allows you to store an additional unsigned 8-bit integer (0 to 255) for each pixel Unity draws to the screen. |
因为 URP 约定“哪些 LightMode 会被用在什么阶段”,很多内置管线里常见的 LightMode(如 ForwardAdd
、Always
)URP 不支持;再加上 URP 的前向路径倾向单 Pass 完成光照,所以你不会再像以前那样“堆很多 Shader Pass 来实现不同阶段”。这不是不能扩展,而是把“阶段控制”上收到了管线层(ScriptableRenderPass)。
NOTE: URP does not support the following LightMode tags:
Always
,ForwardAdd
,PrepassBase
,PrepassFinal
,Vertex
,VertexLMRGBM
,VertexLM
.
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal%4012.0/manual/urp-shaders/urp-shaderlab-pass-tags.html
If you do not set the LightMode
tag in a Pass, URP uses the SRPDefaultUnlit
tag value for that Pass.
Property | Description |
---|---|
UniversalForward | The Pass renders object geometry and evaluates all light contributions. URP uses this tag value in the Forward Rendering Path. |
UniversalGBuffer | The Pass renders object geometry without evaluating any light contribution. Use this tag value in Passes that Unity must execute in the Deferred Rendering Path. |
UniversalForwardOnly | The Pass renders object geometry and evaluates all light contributions, similarly to when LightMode has the UniversalForward value. The difference from UniversalForward is that URP can use the Pass for both the Forward and the Deferred Rendering Paths. Use this value if a certain Pass must render objects with the Forward Rendering Path when URP is using the Deferred Rendering Path. For example, use this tag if URP renders a Scene using the Deferred Rendering Path and the Scene contains objects with shader data that does not fit the GBuffer, such as Clear Coat normals. If a shader must render in both the Forward and the Deferred Rendering Paths, declare two Passes with the UniversalForward and UniversalGBuffer tag values.If a shader must render using the Forward Rendering Path regardless of the Rendering Path that the URP Renderer uses, declare only a Pass with the LightMode tag set to UniversalForwardOnly .If you use the SSAO Renderer Feature, add a Pass with the LightMode tag set to DepthNormalsOnly . For more information, see the DepthNormalsOnly value. |
DepthNormalsOnly | Use this value in combination with UniversalForwardOnly in the Deferred Rendering Path. This value lets Unity render the shader in the Depth and normal prepass. In the Deferred Rendering Path, if the Pass with the DepthNormalsOnly tag value is missing, Unity does not generate the ambient occlusion around the Mesh. |
Universal2D | The Pass renders objects and evaluates 2D light contributions. URP uses this tag value in the 2D Renderer. |
ShadowCaster | The Pass renders object depth from the perspective of lights into the Shadow map or a depth texture. |
DepthOnly | The Pass renders only depth information from the perspective of a Camera into a depth texture. |
Meta | Unity executes this Pass only when baking lightmaps in the Unity Editor. Unity strips this Pass from shaders when building a Player. |
SRPDefaultUnlit | Use this LightMode tag value to draw an extra Pass when rendering objects. Application example: draw an object outline. This tag value is valid for both the Forward and the Deferred Rendering Paths.URP uses this tag value as the default value when a Pass does not have a LightMode tag. |