Mask
UGUI的裁切分为Mask和Mask2D两种
我们先来看Mask。它可以给Mask指定一张裁切图裁切子元素。我们给Mask指定了一张圆形图片,那么子节点下的元素都会被裁切在这个圆形区域中。
Mask的原理就是利用了StencilBuffer(模板缓冲),它里面记录了一个ID,被裁切元素也有StencilBuffer(模板缓冲)的ID,并且和Mask里的比较,相同才会被渲染。
StencilBuffer
看起来好像挺简单的,那么背后的功臣——StencilBuffer,究竟是何方神圣呢?
简单来说,gpu为每个像素点分配一个称之为stencil buffer的1字节大小的内存区域,这个区域可以用于保存或丢弃像素的目的。我们举个简单的例子来说明这个缓冲区的本质。
如上图所示,我们的场景中有1个红色图片和1个绿色图片,黑框范围内是它们重叠部分。一帧渲染开始,首先绿色图片将它覆盖范围的每个像素颜色“画”在屏幕上,然后红色图片也将自己的颜色画在屏幕上,就是图中的效果了。
这种情况下,重叠区域内红色完全覆盖了绿色。接下来,我们为绿色图片添加Mask组件。于是变成了这样:
此时一帧渲染开始,首先绿色图片将它覆盖范围都涂上绿色,同时将每个像素的stencil buffer值设置为1,此时屏幕的stencil buffer分布如下:
然后轮到红色图片“绘画”,它在涂上红色前,会先取出这个点的stencil buffer值判断,在黑框范围内,这个值是1,于是继续画红色;在黑框范围外,这个值是0,于是不再画红色,最终达到了图中的效果。
所以从本质上来讲,stencil buffer是为了实现多个“绘画者”之间互相通信而存在的。由于gpu是流水线作业,它们之间无法直接通信,所以通过这种共享数据区的方式来传递消息,从而达到一些“不可告人”的目的。
unity shader
理解了stencil的原理,我们再来看下它的语法。在unity shader中定义的语法格式如下
(中括号内是可以修改的值,其余都是关键字):- Stencil
- {
- Ref [_Stencil]//Ref表示要比较的值;0-255
- Comp [_StencilComp]//Comp表示比较方法(等于/不等于/大于/小于等);
- Pass [_StencilOp] //Pass/Fail表示当比较通过/不通过时对stencil buffer做什么操作
- //(保留Keep/替换Replace/置0 Zero/增加IncrementSaturate/减少DecrementSaturate等);
- ReadMask [_StencilReadMask]//ReadMask/WriteMask表示取stencil buffer的值时用的mask(即可以忽略某些位);
- WriteMask [_StencilWriteMask]
- }
复制代码 翻译一下就是:将stencil buffer的值与ReadMask与运算,然后与Ref值进行Comp比较,结果为true时进行Pass操作,否则进行Fail操作,操作值写入stencil buffer前先与WriteMask与运算。
UI/Default
最后,我们来看下Unity渲染UI组件时默认使用的Shader——UI/Default(略去了一些不相关内容):- Shader "UI/Default"
- {
- Properties
- {
- [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
- _Color ("Tint", Color) = (1,1,1,1)
-
- _StencilComp ("Stencil Comparison", Float) = 8
- _Stencil ("Stencil ID", Float) = 0
- _StencilOp ("Stencil Operation", Float) = 0
- _StencilWriteMask ("Stencil Write Mask", Float) = 255
- _StencilReadMask ("Stencil Read Mask", Float) = 255
- _ColorMask ("Color Mask", Float) = 15
- [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
- }
- ···
- }
复制代码 以及我们代码中调用的StencilMaterial.Add的内部实现- StencilMaterial.cs
- public static Material Add(Material baseMat, int stencilID, StencilOp operation, CompareFunction compareFunction, ColorWriteMask colorWriteMask, int readMask, int writeMask)
- {
- ···省略
- var newEnt = new MatEntry();
- newEnt.count = 1;
- newEnt.baseMat = baseMat;
- newEnt.customMat = new Material(baseMat);
- newEnt.customMat.hideFlags = HideFlags.HideAndDontSave;
- newEnt.stencilId = stencilID;
- newEnt.operation = operation;
- newEnt.compareFunction = compareFunction;
- newEnt.readMask = readMask;
- newEnt.writeMask = writeMask;
- newEnt.colorMask = colorWriteMask;
- newEnt.useAlphaClip = operation != StencilOp.Keep && writeMask > 0;
- newEnt.customMat.name = string.Format("Stencil Id:{0}, Op:{1}, Comp:{2}, WriteMask:{3}, ReadMask:{4}, ColorMask:{5} AlphaClip:{6} ({7})", stencilID, operation, compareFunction, writeMask, readMask, colorWriteMask, newEnt.useAlphaClip, baseMat.name);
- newEnt.customMat.SetInt("_Stencil", stencilID);
- newEnt.customMat.SetInt("_StencilOp", (int)operation);
- newEnt.customMat.SetInt("_StencilComp", (int)compareFunction);
- newEnt.customMat.SetInt("_StencilReadMask", readMask);
- newEnt.customMat.SetInt("_StencilWriteMask", writeMask);
- newEnt.customMat.SetInt("_ColorMask", (int)colorWriteMask);
- // left for backwards compatability
- if (newEnt.customMat.HasProperty("_UseAlphaClip"))
- newEnt.customMat.SetInt("_UseAlphaClip", newEnt.useAlphaClip ? 1 : 0);
- if (newEnt.useAlphaClip)
- newEnt.customMat.EnableKeyword("UNITY_UI_ALPHACLIP");
- else
- newEnt.customMat.DisableKeyword("UNITY_UI_ALPHACLIP");
- m_List.Add(newEnt);
- return newEnt.customMat;
- }
复制代码 了解了stencil 我们来看mask的源码实现
由于裁切需要同时裁切图片和文本,所以Image和Text都会派生自MaskableGraphic。
如果要让Mask节点下的元素裁切,那么它需要占一个DrawCall,因为这些元素需要一个新的Shader参数来渲染。
如下代码所示,MaskableGraphic实现了IMaterialModifier接口, 而StencilMaterial.Add()就是设置Shader中的裁切参数。- MaskableGraphic.cs
- public virtual Material GetModifiedMaterial(Material baseMaterial)
- {
- var toUse = baseMaterial;
- if (m_ShouldRecalculateStencil)
- {
- var rootCanvas = MaskUtilities.FindRootSortOverrideCanvas(transform);
- //获取模板缓冲值
- m_StencilValue = maskable ? MaskUtilities.GetStencilDepth(transform, rootCanvas) : 0;
- m_ShouldRecalculateStencil = false;
- }
- // if we have a enabled Mask component then it will
- // generate the mask material. This is an optimisation
- // it adds some coupling between components though :(
- Mask maskComponent = GetComponent<Mask>();
- if (m_StencilValue > 0 && (maskComponent == null || !maskComponent.IsActive()))
- {
- //设置模板缓冲值,并且设置在该区域内的显示,不在的裁切掉
- var maskMat = StencilMaterial.Add(toUse, // Material baseMat
- (1 << m_StencilValue) - 1, // 参考值
- StencilOp.Keep, // 不修改模板缓存
- CompareFunction.Equal, // 相等通过测试
- ColorWriteMask.All, // ColorMask
- (1 << m_StencilValue) - 1,// Readmask
- 0);// WriteMas
- StencilMaterial.Remove(m_MaskMaterial);
- //并且更换新的材质
- m_MaskMaterial = maskMat;
- toUse = m_MaskMaterial;
- }
- return toUse;
- }
复制代码 Image对象在进行Rebuild()时,UpdateMaterial()方法中会获取需要渲染的材质,并且判断当前对象的组件是否有继承IMaterialModifier接口,如果有那么它就是绑定了Mask脚本,接着调用上面提到的GetModifiedMaterial方法修改材质上Shader的参数。- Image.cs
- public virtual void Rebuild(CanvasUpdate update)
- {
- if (canvasRenderer.cull)
- return;
- switch (update)
- {
- case CanvasUpdate.PreRender:
- if (m_VertsDirty)
- {
- //开始更新网格
- UpdateGeometry();
- m_VertsDirty = false;
- }
- if (m_MaterialDirty)
- {
- //开始更新材质
- UpdateMaterial();
- m_MaterialDirty = false;
- }
- break;
- }
- }
- public virtual Material materialForRendering
- {
- get
- {
- //遍历UI中的每个Mask组件
- var components = ListPool<Component>.Get();
- GetComponents(typeof(IMaterialModifier), components);
- //并且更新每个Mask组件的模板缓冲材质
- var currentMat = material;
- for (var i = 0; i < components.Count; i++)
- currentMat = (components[i] as IMaterialModifier).GetModifiedMaterial(currentMat);
- ListPool<Component>.Release(components);
- //返回新的材质,用于裁切
- return currentMat;
- }
- }
- protected virtual void UpdateMaterial()
- {
- if (!IsActive())
- return;
- //更新刚刚替换的新的模板缓冲的材质
- canvasRenderer.materialCount = 1;
- canvasRenderer.SetMaterial(materialForRendering, 0);
- canvasRenderer.SetTexture(mainTexture);
- }
复制代码 因为模板缓冲可以提供模板的区域,也就是前面设置的圆形图片,所以最终会将元素裁切到这个圆心图片中。
Mask.GetModifiedMaterial
- Mask.cs
- /// Stencil calculation time!
- public virtual Material GetModifiedMaterial(Material baseMaterial)
- {
- if (!MaskEnabled())
- return baseMaterial;
- var rootSortCanvas = MaskUtilities.FindRootSortOverrideCanvas(transform);
- var stencilDepth = MaskUtilities.GetStencilDepth(transform, rootSortCanvas);
- // stencil只支持最大深度为8的遮罩
- if (stencilDepth >= 8)
- {
- Debug.LogError(&#34;Attempting to use a stencil mask with depth > 8&#34;, gameObject);
- return baseMaterial;
- }
- int desiredStencilBit = 1 << stencilDepth;
- // if we are at the first level...
- // we want to destroy what is there
- if (desiredStencilBit == 1)
- {
- var maskMaterial = StencilMaterial.Add(baseMaterial, 1, StencilOp.Replace, CompareFunction.Always, m_ShowMaskGraphic ? ColorWriteMask.All : 0);
- StencilMaterial.Remove(m_MaskMaterial);
- m_MaskMaterial = maskMaterial;
- var unmaskMaterial = StencilMaterial.Add(baseMaterial, 1, StencilOp.Zero, CompareFunction.Always, 0);
- StencilMaterial.Remove(m_UnmaskMaterial);
- m_UnmaskMaterial = unmaskMaterial;
- graphic.canvasRenderer.popMaterialCount = 1;
- graphic.canvasRenderer.SetPopMaterial(m_UnmaskMaterial, 0);
- return m_MaskMaterial;
- }
- //otherwise we need to be a bit smarter and set some read / write masks
- var maskMaterial2 = StencilMaterial.Add(baseMaterial, desiredStencilBit | (desiredStencilBit - 1), StencilOp.Replace, CompareFunction.Equal, m_ShowMaskGraphic ? ColorWriteMask.All : 0, desiredStencilBit - 1, desiredStencilBit | (desiredStencilBit - 1));
- StencilMaterial.Remove(m_MaskMaterial);
- m_MaskMaterial = maskMaterial2;
- graphic.canvasRenderer.hasPopInstruction = true;
- var unmaskMaterial2 = StencilMaterial.Add(baseMaterial, desiredStencilBit - 1, StencilOp.Replace, CompareFunction.Equal, 0, desiredStencilBit - 1, desiredStencilBit | (desiredStencilBit - 1));
- StencilMaterial.Remove(m_UnmaskMaterial);
- m_UnmaskMaterial = unmaskMaterial2;
- graphic.canvasRenderer.popMaterialCount = 1;
- graphic.canvasRenderer.SetPopMaterial(m_UnmaskMaterial, 0);
- return m_MaskMaterial;
- }
复制代码 Mask 组件调用了模板材质球构建了一个自己的材质球,因此它使用了实时渲染中的模板方法来裁切不需要显示的部分,所有在 Mask 组件后面的物体都会进行裁切。
我们可以说 Mask 是在 GPU 中做的裁切,使用的方法是着色器中的模板方法。
Mask2D
接着我们再来看看Mask2D的原理,在前面介绍Canvas.willRenderCanvases()时在PerformUpdate方法中会调用ClipperRegistry.instance.Cull();来处理界面中所有的Mask2D裁切。- CanvasUpdateRegistry.cs
- protected CanvasUpdateRegistry()
- {
- Canvas.willRenderCanvases += PerformUpdate;
- }
- private void PerformUpdate()
- {
- //...略
- // 开始裁切Mask2D
- ClipperRegistry.instance.Cull();
- //...略
- }
- ClipperRegistry.cs
- public void Cull()
- {
- for (var i = 0; i < m_Clippers.Count; ++i)
- {
- m_Clippers[i].PerformClipping();
- }
- }
复制代码 Mask2D会在OnEnable()方法中,将当前组件注册ClipperRegistry.Register(this);
这样在上面ClipperRegistry.instance.Cull();方法时就可以遍历所有Mask2D组件并且调用它们的PerformClipping()方法了。
PerformClipping()方法,需要找到所有需要裁切的UI元素,因为Image和Text都继承了IClippable接口,最终将调用Cull()进行裁切。- RectMask2D.cs
- protected override void OnEnable()
- {
- //注册当前RectMask2D裁切对象,保证下次Rebuild时可进行裁切。
- base.OnEnable();
- m_ShouldRecalculateClipRects = true;
- ClipperRegistry.Register(this);
- MaskUtilities.Notify2DMaskStateChanged(this);
- }
- public virtual void PerformClipping()
- {
- //TODO See if an IsActive() test would work well here or whether it might cause unexpected side effects (re case 776771)
- // if the parents are changed
- // or something similar we
- // do a recalculate here
- //重新计算裁切区域
- if (m_ShouldRecalculateClipRects)
- {
- MaskUtilities.GetRectMasksForClip(this, m_Clippers);
- m_ShouldRecalculateClipRects = false;
- }
- // get the compound rects from
- // the clippers that are valid
- bool validRect = true;
- Rect clipRect = Clipping.FindCullAndClipWorldRect(m_Clippers, out validRect);
- bool clipRectChanged = clipRect != m_LastClipRectCanvasSpace;
- if (clipRectChanged || m_ForceClip)
- {
- foreach (IClippable clipTarget in m_ClipTargets)
- //把裁切区域传到每个UI元素的Shader中[划重点!!!]
- clipTarget.SetClipRect(clipRect, validRect);
- m_LastClipRectCanvasSpace = clipRect;
- m_LastValidClipRect = validRect;
- }
- foreach (IClippable clipTarget in m_ClipTargets)
- {
- var maskable = clipTarget as MaskableGraphic;
- if (maskable != null && !maskable.canvasRenderer.hasMoved && !clipRectChanged)
- continue;
- clipTarget.Cull(m_LastClipRectCanvasSpace, m_LastValidClipRect);
- }
- }
- MaskableGraphic.cs
- public virtual void Cull(Rect clipRect, bool validRect)
- {
- var cull = !validRect || !clipRect.Overlaps(rootCanvasRect, true);
- UpdateCull(cull);
- }
- private void UpdateCull(bool cull)
- {
- var cullingChanged = canvasRenderer.cull != cull;
- canvasRenderer.cull = cull;
- if (cullingChanged)
- {
- UISystemProfilerApi.AddMarker(&#34;MaskableGraphic.cullingChanged&#34;, this);
- m_OnCullStateChanged.Invoke(cull);
- SetVerticesDirty();
- }
- }
复制代码 RectMask2D会将RectTransform的区域作为_ClipRect传入Shader中。
Stencil Ref 的值是0 表示它并没有使用模板缓冲比较,
如果只是矩形裁切,RectMask2D不需要一个无效的渲染用于模板比较,所以RectMask2D的效率会比Mask要高。
在Shader的Frag处理像素中,被裁切掉的区域是通过UnityGet2DClipping()根据_ClipRect比较当前像素是否在裁切区域中,如果不在,将Color.a变成了透明。- Shader &#34;UI/Default&#34;
- {
- //...略
- fixed4 frag(v2f IN) : SV_Target
- {
- half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;
- //根据_ClipRect比较当前像素是否在裁切区域中,如果不在颜色将设置成透明
- #ifdef UNITY_UI_CLIP_RECT
- color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
- #endif
- #ifdef UNITY_UI_ALPHACLIP
- clip (color.a - 0.001);
- #endif
- return color;
- }
- }
复制代码 参考
Unity mask的分析与理解 |