全部基于屏幕后处理
一、深度纹理和法线纹理生成的条件
深度纹理来自NDC坐标表示下的z值。
深度纹理和法线纹理的生成需要以下几个条件:
首先是SubShader的着色器替换标签必须设置为 Opaque。
然后便是该SubShader的Pass通道必须包含一个用于投射阴影的Pass。
最后便是摄像机脚本设置。
二、全局雾效
基于屏幕后处理的雾效,使用深度纹理重构像素的世界坐标,实现远处有雾且浓,近处无雾或淡。
世界坐标的重构有两种方法,第一个是先求NDC下的坐标表示,然后用视角*投影矩阵的逆矩阵进行重构,但要在片元着色器中进行两次矩阵计算,还是挺费力的。
第二个是利用向量,我们求出每个像素到摄像机的向量,然后和摄像机的世界坐标相加,得到重构的世界坐标,这个向量我们可以在顶点着色器中先求出近平面的四个角的向量,然后利用插值特性得到像素的向量。
第一个写法:
先求NDC坐标表示,这个坐标一定要转化到-1到1之间,因为Unity内部使用计算就是按这个标准,我们必须把所有的东西都和Unity保持一致,这样计算才不会出错。为什么到特意提到这个点,说多了都是泪,学Shader到现在踩的巨深的一次坑,Unity在编辑模式下默认使用DX的API,DX对于深度的处理是按(1,0),1才是近平面,但是书上只是简单说DX是(0,1)完全没有提及方向是反的。找了一个下午,差点怀疑人生。
关于在NDC下在反向变换到齐次裁剪空间下时,我们并不知道w分量的值,没有办法做透视除法的逆操作,这个网上博客有数学证明,我们可以用世界坐标的w值除以世界坐标,得到的结果仍然是正确的。
脚本:
using System;
using UnityEngine;
[ExecuteInEditMode]
public class RenderImage : MonoBehaviour
{
public Shader shader;
public Mesh mesh;
public GameObject gameObject;
private Camera _camera;
private Material _material;
[Header("雾强度")] public float fogStrength = 1;
[Header("雾颜色")] public Color fogColor = Color.white;
[Header("雾起始高度")] public float fogStartDis = 0;
[Header("雾结束高度")] public float fogEndDis = 2;
[Header("启用雾")] public bool key;
// Start is called before the first frame update
void Awake()
{
_camera = GetComponent<Camera>();
_camera.depthTextureMode |= DepthTextureMode.Depth;
}
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
if (!key)
{
_material = null;
}
else
{
_material = new Material(shader);
}
if (_material != null)
{
//Shader内部有一个VP矩阵,但那个矩阵无法提供转置功能,还是用API来的实在
Matrix4x4 temp = _camera.projectionMatrix * _camera.worldToCameraMatrix;
_material.SetMatrix("_ProjectionView", temp.inverse);
_material.SetFloat("_FogStrenth", fogStrength);
_material.SetColor("_FogColor", fogColor);
_material.SetFloat("_FogStart", fogStartDis);
_material.SetFloat("_FogEnd", fogEndDis);
Graphics.Blit(src, dest, _material);
}
else
{
Graphics.Blit(src, dest);
}
}
}
Shader:
Shader "Custom/Test1"
{
Properties
{
_MainTex("主帖图",2D)="white"{}
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
sampler2D _CameraDepthTexture;
float4x4 _ProjectionView;
float _FogStrenth;
float4 _FogColor;
float _FogStart;
float _FogEnd;
struct a2v
{
float4 vertex:POSITION;
float4 texcoord:TEXCOORD0;
};
struct v2f
{
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord;
return o;
}
fixed4 frag(v2f i):SV_Target
{
//采样深度,此时的深度处于(0,1)之间.
float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv);
//我们需要将此时的屏幕坐标映射回NDC
float4 NDC_POS = float4(i.uv.x * 2 - 1, i.uv.y * 2 - 1, -(depth * 2 - 1), 1);
float4 rowWorldPos = mul(_ProjectionView, NDC_POS);
rowWorldPos = rowWorldPos / rowWorldPos.w;
float fog = (_FogEnd - rowWorldPos.y) / (_FogEnd - _FogStart);
fog = saturate(fog * _FogStrenth);
fixed4 color = tex2D(_MainTex, i.uv);
color.rgb = lerp(color.rgb, _FogColor.rgb, fog);
return fixed4(color.rgb, 1);
}
ENDCG
}
}
}
结果不演示,和第二个一样。
第二个写法:
先算出来摄像机原点离近平面的四个点的向量,然后算出来真正的深度比例,我们采样得到的深度值只是在Z轴上的值,实际中我们要算的是向量方向上的。
脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class RenderImage : MonoBehaviour
{
public Shader shader;
private Camera _camera;
private Material _material;
[Header("雾强度")]public float fogStrength=1;
[Header("雾颜色")] public Color fogColor=Color.white;
[Header("雾起始高度")] public float fogStartDis=0;
[Header("雾结束高度")] public float fogEndDis=2;
[Header("启用雾")]public bool key;
// Start is called before the first frame update
void Awake()
{
if (shader == null)
{
Debug.Log("Shader为空");
}
else
{
_camera = GetComponent<Camera>();
_camera.depthTextureMode |= DepthTextureMode.Depth;
//_material = new Material(shader);
}
}
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
if (!key)
{
_material = null;
}
else
{
_material = new Material(shader);
}
if (_material != null)
{
//计算四个向量的前期准备
float temp =_camera.nearClipPlane* Mathf.Tan(_camera.fieldOfView * 0.5f*Mathf.Deg2Rad);
Vector3 up = _camera.transform.up * temp;
Vector3 right = _camera.transform.right* _camera.aspect * temp ;
//开始计算四个向量,但此时向量只有方向信息
var nearClipPlane = _camera.nearClipPlane;
Vector3 temp1 = _camera.transform.forward * nearClipPlane;
//左上
Vector3 LT = temp1 + up - right;
//左下
Vector3 LB = temp1 - up - right;
//右上
Vector3 RT = temp1 + up + right;
//右下
Vector3 RB = temp1 - up + right;
//计算真正的深度比例,送给片元着色器用于得到准确的深度
//知道一个像素的深度,我们可以根据相似三角形计算比例
float scale = LT.magnitude / nearClipPlane;
//对四个向量进行深度比例的处理,这样的向量就包含了真正的距离和方向
LT.Normalize();
LT *= scale;
LB.Normalize();
LB *= scale;
RT.Normalize();
RT *= scale;
RB.Normalize();
RB *= scale;
//我们利用一个矩阵存储四个向量,先初始化为单位矩阵
Matrix4x4 temp2=Matrix4x4.identity;
temp2.SetRow(0,LT);
temp2.SetRow(1,LB);
temp2.SetRow(2,RT);
temp2.SetRow(3,RB);
//材质值传递
_material.SetMatrix("_CornerVector",temp2);
_material.SetFloat("_FogStrenth",fogStrength);
_material.SetColor("_FogColor",fogColor);
_material.SetFloat("_FogStart",fogStartDis);
_material.SetFloat("_FogEnd",fogEndDis);
Graphics.Blit(src,dest,_material);
}
else
{
Graphics.Blit(src,dest);
}
}
}
Shader:
Shader "Custom/Test0"
{
Properties
{
//不写这句话就是灰,试了半小时给试出来了
//偏偏别的都能过,就纹理必须写。。。
_MainTex("主帖图",2D)="white"{}
}
SubShader
{
Pass
{
Tags
{
"LightMode"="ForwardBase"
}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4x4 _CornerVector;
float _FogStrenth;
float4 _FogColor;
float _FogStart;
float _FogEnd;
//声明获取深度纹理
sampler2D _CameraDepthTexture;
struct a2v
{
float4 vertex:POSITION;
float4 texcoord:TEXCOORD0;
};
struct v2f
{
float4 pos:SV_POSITION;
float2 uv:TEXCOORD0;
float4 dir:TEXCOORD1;
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord;
int index ;
//关系对应好
if (v.texcoord.x < 0.5 && v.texcoord.y < 0.5)
{
//左下
index = 1;
}
else if (v.texcoord.x > 0.5 && v.texcoord.y < 0.5)
{
//右下
index = 3;
}
else if (v.texcoord.x > 0.5 && v.texcoord.y > 0.5)
{
//右上
index = 2;
}
else
{
//左上
index = 0;
}
o.dir = _CornerVector[index];
return o;
}
fixed4 frag(v2f i):SV_Target
{
//解析深度
float depth = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv));
//世界坐标计算
float3 worldPos = _WorldSpaceCameraPos + depth * i.dir;
//雾效公式,(高度雾,参数是y
//这种写法如果y值越低,雾越浓,即便是y值超过了起始点
float fog = (_FogEnd - worldPos.y) / (_FogEnd - _FogStart);
//在后面再乘一个值把上面的影响消掉,但注意,雾的起始高度要足够低,
//否则会影响fog的值
fog = saturate(fog)* _FogStrenth*saturate(worldPos.y-_FogStart);
fixed4 color = tex2D(_MainTex, i.uv);
color.rgb = (1-fog)*color.rgb+fog*_FogColor.rgb;// lerp(color.rgb, _FogColor.rgb, fog);
return color;
}
ENDCG
}
}
}
结果:
可以看到即便是场景外雾也不会生效,因为场景外的高度过低
场景为Unity商店免费场景。
基于高度雾,还有距离雾。详情请看基础案例系列。
三、边缘检测
基于深度与法线纹理的边缘检测。
采样深度纹理和法线纹理,然后利用Roberts算子进行评估。关于为什么要两个同时用,可以多想想某些算不上特殊情况的特殊情况。
脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class RenderImage : MonoBehaviour
{
public Shader shader;
private Camera _camera;
private Material _material;
[Header("描边强度")][Range(0,1)]public float edgeStrength=1;
[Header("描边颜色")] public Color edgeColor=Color.black;
[Header("是否只显示边缘")] public float edgeOnly=0;
//阈值越小,检测越严格
[Header("深度判断阈值")] private float depth=1f;
[Header("法线判断阈值")] private float noraml=1;
// Start is called before the first frame update
void Awake()
{
if (shader == null)
{
Debug.Log("Shader为空");
}
else
{
_camera = GetComponent<Camera>();
_camera.depthTextureMode |= DepthTextureMode.DepthNormals;
_material = new Material(shader);
}
}
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
if (_material != null)
{
_material.SetFloat("_EdgeStrength",edgeStrength);
_material.SetColor("_EdgeColor",edgeColor);
_material.SetFloat("_EdgeOnly",edgeOnly);
_material.SetFloat("_DepthThreshold",depth);
_material.SetFloat("_NoramlThreshold",noraml);
Graphics.Blit(src,dest,_material);
}
else
{
Graphics.Blit(src,dest);
}
}
}
Shader:
Shader "Custom/Test0"
{
Properties
{
_MainTex("主帖图",2D)="white"{}
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_TexelSize;
float _EdgeStrength;
float4 _EdgeColor;
float _EdgeOnly;
float _DepthThreshold;
float _NoramlThreshold;
//声明获取深度法线纹理
sampler2D _CameraDepthNormalsTexture;
struct a2v
{
float4 vertex:POSITION;
float4 texcoord:TEXCOORD0;
};
struct v2f
{
float4 pos:SV_POSITION;
float2 uv[5]:TEXCOORD0;
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
//和高斯模糊一样,本来也是要分x方向卷积和y方向卷积
//但我们可以用一些手段混在一起计算
o.uv[0] = v.texcoord;
//前两个为针对Gy方向的
o.uv[1] = v.texcoord + _MainTex_TexelSize.xy * float2(1, 1) * _EdgeStrength;
o.uv[2] = v.texcoord + _MainTex_TexelSize.xy * float2(-1, -1) * _EdgeStrength;
//后两个为针对Gx方向的
o.uv[3] = v.texcoord + _MainTex_TexelSize.xy * float2(-1, 1) * _EdgeStrength;
o.uv[4] = v.texcoord + _MainTex_TexelSize.xy * float2(1, -1) * _EdgeStrength;
return o;
}
int EdgeJudge(float4 sample1, float4 sample2)
{
//先解析深度与法线
float2 sample1_Normal = sample1.xy;
float sample1_Depth = DecodeFloatRG(sample1.zw);
float2 sampler2_Normal = sample2.xy;
float sampler2_Depth = DecodeFloatRG(sample2.zw);
//计算两个采样点的插值
float2 difference_Noraml = abs(sample1_Normal - sampler2_Normal) * _NoramlThreshold;
float difference_Depth = abs(sample1_Depth - sampler2_Depth) * _DepthThreshold;
int jugeNormal = (difference_Noraml.x + difference_Noraml.y) < 0.1;
int jugeDepth=difference_Depth<0.1*sample1_Depth;
//这里做了一个改动,书上用的if判断,
//不过不知道CG内部是不是if
return saturate(jugeDepth*jugeNormal*100);
}
fixed4 frag(v2f i):SV_Target
{
//四个点采样
float4 sample1 = tex2D(_CameraDepthNormalsTexture, i.uv[1]);
float4 sample2 = tex2D(_CameraDepthNormalsTexture, i.uv[2]);
float4 sample3 = tex2D(_CameraDepthNormalsTexture, i.uv[3]);
float4 sample4 = tex2D(_CameraDepthNormalsTexture, i.uv[4]);
//送去做边缘判定
fixed edge = 1.0;
edge *= EdgeJudge(sample1, sample2);
edge *= EdgeJudge(sample3, sample4);
fixed4 edgeColor=lerp(_EdgeColor,tex2D(_MainTex,i.uv[0]),edge);
fixed4 onlyEdge=lerp(_EdgeColor,float4(1,1,1,1),edge);
return lerp(edgeColor,onlyEdge,_EdgeOnly);
}
ENDCG
}
}
}
结果还行,关于Shader中的深度和法线的判断,咱也没想明白为什么这样判断。
书上还提到选中物体描边,对某些问题实行描边,这个也不难,用ComputeScreenPos函数获取对应位置的纹理坐标,然后作判断,想法待实验。
深度纹理能做的事情有很多,比如屏幕空间的环境光遮蔽,会让物体相连处打上阴影,而且比实时渲染快速效果好,还有角色护盾,海边白沫等等。