平面檢測是很多AR應用的基礎,無論是ARKit還是ARCore,都提供平面檢測功能。同時,平面也是可跟蹤對象,在前幾節中我們知道,ARFoundation使用ARPlaneManager管理器來管理平面。
(一)平面檢測管理
AR中檢測平面的原理:ARFoundation對攝像機獲取的圖像進行處理,分離圖像中的特徵點(這些特徵點往往都是圖像中明暗、強弱、顏色變化較大的點),利用VIO和IMU跟蹤這些特徵點的三維空間信息,在跟蹤過程中,對特徵點信息進行處理,並嘗試用空間中位置相近或者符合一定規律的特徵點構建平面,如果成功就是檢測出了平面。平面有其位置、方向和邊界信息,ARPlaneManager負責如何檢測平面以及管理這些檢測出來的平面,但它並不負責渲染平面。
在ARPlaneManager中,我們可以設置平面檢測的方式,如水平平面(Horizontal)、垂直平面(Vertical)、水平平面&垂直平面(Everything)或者不檢測平面(Nothing),因爲檢測平面也是一個消耗性能的工作,所以根據應用需要選擇合適的檢測方式可以優化應用性能,如下圖所示。
ARPlaneManager每幀都會進行平面檢測,會添加新檢測到的平面、更新現有平面、移除過時的平面。當一個新的平面被檢測到時,ARPlaneManager會實例化一個平面Prefab來表示該平面,如果開發中ARPlaneManager的Plane Prefab屬性沒有對賦值,ARPlaneManager將會實例化一個空對象,並在這個空對象上掛載ARPlane組件,ARPlane組件包含了該平面的相關信息數據。
ARPlaneManager組件還有一個planesChanged事件,開發人員可以註冊這個事件,以便在平面發生改變時進行相應處理。
(二)可視化平面
在ARFoundation中,ARPlaneManager並不負責平面的可視化渲染,而由其Plane Prefab屬性指定的預製體負責。在前文中,我們新建了一個AR Default Plane對象作爲預製體,該預製體上掛載瞭如下圖所示組件。
AR Plane組件負責該平面各類屬性事宜,如是否在移除平面時銷燬該實例化對象,控制可劃分爲同一平面的特徵點的閥值(上圖中紅框屬性,只有偏差在這個閥值內的特徵點纔可歸屬爲同一平面,這影響平面檢測。);AR Plane Mesh Visualizer該組件主要是從邊界特徵點和其他特徵點三角化生成一個平面網格,有這個平面網格後自然就可以使用Mesh Renderer採用合適材質渲染出來了;默認平面預製體還有一個Line Renderer,它負責渲染平面可視化後的邊界連線。所以使用默認平面預製體可視已檢測到的平面如下圖所示。
(三)個性化可視平面
對已檢測到的平面默認的可視化顯得有些生硬和突兀,有時我們需要更加友好的界面,這時我們就需要對已檢測到的平面定製我們自己個性的可視方案。
爲達到更好的視覺效果,處理的思路如下:
1)、不顯示黑色邊框;
2)、重新制作一個渲染材質和Shader腳本,紋理我們使用半透明的PNG,Shader腳本渲染這個半透明的紋理,將紋理空白區域都鏤空;
3)、編寫一個漸隱的腳本,讓邊緣的紋理漸隱,達到更好的視覺過渡。
按照以上思路,我們直接對AR Default Plane預製體進行改造。
1)、刪除AR Default Plane預製體上的Line Renderer組件;
2)、編寫如下所示Shader,製作一張PNG半透明紋理,並新建一個利用這個Shader的材質。
Shader "Unlit/FeatheredPlaneShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_TexTintColor("Texture Tint Color", Color) = (1,1,1,1)
_PlaneColor("Plane Color", Color) = (1,1,1,1)
}
SubShader
{
Tags { "RenderType"="Transparent" "Queue"="Transparent" }
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 uv2 : TEXCOORD1;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float3 uv2 : TEXCOORD1;
};
sampler2D _MainTex;
float4 _MainTex_ST;
fixed4 _TexTintColor;
fixed4 _PlaneColor;
float _ShortestUVMapping;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.uv2 = v.uv2;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv) * _TexTintColor;
col = lerp( _PlaneColor, col, col.a);
// Fade out from as we pass the edge.
// uv2.x stores a mapped UV that will be "1" at the beginning of the feathering.
// We fade until we reach at the edge of the shortest UV mapping.
// This is the remmaped UV value at the vertex.
// We choose the shorted one so that ll edges will fade out completely.
// See ARFeatheredPlaneMeshVisualizer.cs for more details.
col.a *= 1-smoothstep(1, _ShortestUVMapping, i.uv2.x);
return col;
}
ENDCG
}
}
}
在這個Shader中,有三個參數,Texture即爲紋理,將我們製作的紋理賦給它,TextureTintColor爲紋理顯示,我們要讓透明的十字星號顯示出來,Alpha設置爲220,PlaneColor爲平面的背景色,這裏我們不要背景色,Alpha設置爲0,如下圖所示。
3)、新建一個C#腳本文件,命名爲ARFeatheredPlaneMeshVisualizer.cs,編寫如下代碼:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
/// <summary>
/// This plane visualizer demonstrates the use of a feathering effect
/// at the edge of the detected plane, which reduces the visual impression
/// of a hard edge.
/// </summary>
[RequireComponent(typeof(ARPlaneMeshVisualizer), typeof(MeshRenderer), typeof(ARPlane))]
public class ARFeatheredPlaneMeshVisualizer : MonoBehaviour
{
[Tooltip("The width of the texture feathering (in world units).")]
[SerializeField]
float m_FeatheringWidth = 0.2f;
/// <summary>
/// The width of the texture feathering (in world units).
/// </summary>
public float featheringWidth
{
get { return m_FeatheringWidth; }
set { m_FeatheringWidth = value; }
}
void Awake()
{
m_PlaneMeshVisualizer = GetComponent<ARPlaneMeshVisualizer>();
m_FeatheredPlaneMaterial = GetComponent<MeshRenderer>().material;
m_Plane = GetComponent<ARPlane>();
}
void OnEnable()
{
m_Plane.boundaryChanged += ARPlane_boundaryUpdated;
}
void OnDisable()
{
m_Plane.boundaryChanged -= ARPlane_boundaryUpdated;
}
void ARPlane_boundaryUpdated(ARPlaneBoundaryChangedEventArgs eventArgs)
{
GenerateBoundaryUVs(m_PlaneMeshVisualizer.mesh);
}
/// <summary>
/// Generate UV2s to mark the boundary vertices and feathering UV coords.
/// </summary>
/// <remarks>
/// The <c>ARPlaneMeshVisualizer</c> has a <c>meshUpdated</c> event that can be used to modify the generated
/// mesh. In this case we'll add UV2s to mark the boundary vertices.
/// This technique avoids having to generate extra vertices for the boundary. It works best when the plane is
/// is fairly uniform.
/// </remarks>
/// <param name="mesh">The <c>Mesh</c> generated by <c>ARPlaneMeshVisualizer</c></param>
void GenerateBoundaryUVs(Mesh mesh)
{
int vertexCount = mesh.vertexCount;
// Reuse the list of UVs
s_FeatheringUVs.Clear();
if (s_FeatheringUVs.Capacity < vertexCount) { s_FeatheringUVs.Capacity = vertexCount; }
mesh.GetVertices(s_Vertices);
Vector3 centerInPlaneSpace = s_Vertices[s_Vertices.Count - 1];
Vector3 uv = new Vector3(0, 0, 0);
float shortestUVMapping = float.MaxValue;
// Assume the last vertex is the center vertex.
for (int i = 0; i < vertexCount - 1; i++)
{
float vertexDist = Vector3.Distance(s_Vertices[i], centerInPlaneSpace);
// Remap the UV so that a UV of "1" marks the feathering boudary.
// The ratio of featherBoundaryDistance/edgeDistance is the same as featherUV/edgeUV.
// Rearrange to get the edge UV.
float uvMapping = vertexDist / Mathf.Max(vertexDist - featheringWidth, 0.001f);
uv.x = uvMapping;
// All the UV mappings will be different. In the shader we need to know the UV value we need to fade out by.
// Choose the shortest UV to guarentee we fade out before the border.
// This means the feathering widths will be slightly different, we again rely on a fairly uniform plane.
if (shortestUVMapping > uvMapping) { shortestUVMapping = uvMapping; }
s_FeatheringUVs.Add(uv);
}
m_FeatheredPlaneMaterial.SetFloat("_ShortestUVMapping", shortestUVMapping);
// Add the center vertex UV
uv.Set(0, 0, 0);
s_FeatheringUVs.Add(uv);
mesh.SetUVs(1, s_FeatheringUVs);
mesh.UploadMeshData(false);
}
static List<Vector3> s_FeatheringUVs = new List<Vector3>();
static List<Vector3> s_Vertices = new List<Vector3>();
ARPlaneMeshVisualizer m_PlaneMeshVisualizer;
ARPlane m_Plane;
Material m_FeatheredPlaneMaterial;
}
將ARFeatheredPlaneMeshVisualizer掛載到AR Default Plane預製體上,完成之後應該如下圖所示:
編譯運行,效果如下所示,視覺效果要好很多了。
注:本文Shader與ARFeatheredPlaneMeshVisualizer.cs腳本均取自參考代碼工程,爲方便讀者,我已將圖片、Shader、腳本分離出來,讀者也可以在 這裏 下載,直接就可以在工程裏使用。
參考代碼
arfoundation-samples arfoundation-samples