当前位置:网站首页>Unity shader depth of field effect
Unity shader depth of field effect
2022-07-28 17:07:00 【Morita Rinko】
Realization effect
Depth of field effect
Realize the idea
It consists of two figures , They are the fuzzy state in the distance and the clear state near , Judge the distance between the object and the camera according to the depth of the object, and determine the state of the object . Two graphs are interpolated , The closer you get, the closer you get to the clear image .
Code
Script code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DepthOfField : PostEffectsBase
{
public Shader bloomShader;
private Material bloomMaterial = null;
public Material material
{
get
{
bloomMaterial = CheckShaderAndCreateMaterial(bloomShader, bloomMaterial);
return bloomMaterial;
}
}
// The number of iterations
[Range(0, 4)]
public int iterations = 3;
// Fuzzy range
[Range(0.2f, 3.0f)]
public float blurSpread = 0.6f;
// Scaling factor
[Range(1, 8)]
public int downSample = 2;
[Range(0.0f, 50f)]
// The distance between the dividing line near and far
public float Threshold = 10f;
[Range(0.0f, 1.0f)]
// Fuzzy coefficient near
public float NearBlurSize = 0.0f;
// The blur coefficient in the distance
[Range(0.0f, 1.0f)]
public float FarBlurSize = 1.0f;
private Camera myCamera;
public Camera camera
{
get
{
if (myCamera == null)
{
myCamera = GetComponent<Camera>();
}
return myCamera;
}
}
private Transform myCameraTransform;
public Transform cameraTransform
{
get
{
if (myCameraTransform == null)
{
myCameraTransform = camera.transform;
}
return myCameraTransform;
}
}
// Start is called before the first frame update
private void OnEnable()
{
camera.depthTextureMode |= DepthTextureMode.Depth;
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (material != null)
{
// The ginseng
material.SetFloat("_Threshold", Threshold);
material.SetFloat("_NearBlurSize", NearBlurSize);
material.SetFloat("_FarBlurSize", FarBlurSize);
int rtW = source.width / downSample;
int rtH = source.height / downSample;
RenderTexture buffer0 = RenderTexture.GetTemporary(rtW, rtH, 0);
buffer0.filterMode = FilterMode.Bilinear;
// Deliver clear images
buffer0 = source;
for (int i = 0; i < 3; i++)
{
material.SetFloat("_BlurSize", 1.0f + i * blurSpread);
RenderTexture buffer1 = RenderTexture.GetTemporary(rtW, rtH, 0);
Graphics.Blit(buffer0, buffer1, material, 0);
RenderTexture.ReleaseTemporary(buffer0);
buffer0 = buffer1;
buffer1 = RenderTexture.GetTemporary(rtW, rtH, 1);
Graphics.Blit(buffer0, buffer1, material, 1);
RenderTexture.ReleaseTemporary(buffer0);
buffer0 = buffer1;
}
// The extracted image is blurred and stored in the texture
material.SetTexture("_Blur", buffer0);
// Use the fourth pass Merge the blurred image with the original
Graphics.Blit(source, destination, material,2);
RenderTexture.ReleaseTemporary(buffer0);
}
else
{
Graphics.Blit(source, destination);
}
}
}
shader
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
Shader "Custom/depthoffield"
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" {
}
}
SubShader
{
CGINCLUDE
#include "unityCG.cginc"
sampler2D _MainTex;
half4 _MainTex_TexelSize;
sampler2D _Blur;
float _Threshold;
sampler2D _CameraDepthTexture;
float _NearBlurSize;
float _FarBlurSize;
// Structure diagram of fragment shader of mixed image
struct v2fblur{
float4 pos:SV_POSITION;
// Clear and fuzzy texture coordinates are consistent
half2 uv:TEXCOORD0;
// Depth texture coordinates
half2 uv_depth:TEXCOORD1;
};
// Vertex shader
v2fblur vertBlur(appdata_img v){
v2fblur o;
o.pos =UnityObjectToClipPos(v.vertex);
o.uv =v.texcoord;
o.uv_depth =v.texcoord;
// Platform differentiation
#if UNITY_UV_STARTS_AT_TOP
if(_MainTex_TexelSize.y<0.0){
o.uv.y=1.0-o.uv.y;
}
#endif
return o;
}
// Fragment Shader
fixed4 fragBlur(v2fblur i):SV_Target{
// Clear images
fixed4 maincolor = tex2D(_MainTex,i.uv);
// Blur the image
fixed4 blurcolor =tex2D(_Blur,i.uv);
// Depth value
float linearDepth =LinearEyeDepth(SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture,i.uv_depth));
// Interpolation with critical value
float dis = (linearDepth-_Threshold);
if(dis<=0){
dis*=_NearBlurSize;
}else{
dis*=_FarBlurSize;
}
// Limit to [0,1]
dis = clamp(abs(dis),0,1);
// Interpolation color , The fuzzy coefficient near is small , Far away
return lerp(maincolor,blurcolor,dis);
}
ENDCG
Tags{
"RenderType"="Opaque"}
ZTest Always Cull Off ZWrite Off
// blurred
UsePass "Custom/Chapter12-GaussianBlur/GAUSSIAN_BLUR_VERTICAL"
UsePass "Custom/Chapter12-GaussianBlur/GAUSSIAN_BLUR_HORIZONTAL"
// Blend images pass
Pass{
CGPROGRAM
#pragma vertex vertBlur
#pragma fragment fragBlur
ENDCG
}
}
FallBack "Diffuse"
}
边栏推荐
- Ugui learning notes (II) Scrollview related
- Detailed steps for setting up SUSE storage6 environment – win10 + VMware Workstation
- Easypoi --- excel file export
- 【深度学习】:《PyTorch入门到项目实战》:简洁代码实现线性神经网络(附代码)
- Alibaba cloud MSE supports go language traffic protection
- How should I understand craft
- Rsync service deployment and parameter details
- Ugui learning notes (IV) ugui event system overview and Usage Summary
- : No such file or directory
- 【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
猜你喜欢
![[deep learning]: day 8 of pytorch introduction to project practice: weight decline (including source code)](/img/19/18d6e94a1e0fa4a75b66cf8cd99595.png)
[deep learning]: day 8 of pytorch introduction to project practice: weight decline (including source code)

大学生参加六星教育PHP培训,找到了薪水远超同龄人的工作

Comprehensively design an oppe homepage -- after sales service of the page

Re13: read the paper gender and racial stereotype detection in legal opinion word embeddings

Re12:读论文 Se3 Semantic Self-segmentation for Abstractive Summarization of Long Legal Documents in Low

Do you really understand CMS garbage collector?

Ugui learning notes (II) Scrollview related
![[deep learning]: day 9 of pytorch introduction to project practice: dropout implementation (including source code)](/img/19/18d6e94a1e0fa4a75b66cf8cd99595.png)
[deep learning]: day 9 of pytorch introduction to project practice: dropout implementation (including source code)
Read excel xlsx format file in unity

在AD中添加差分对及连线
随机推荐
[deep learning]: the second day of pytorch introduction to project practice: realize linear regression from zero (including detailed code)
Ugui learning notes (III) summary of the use of each control
Interesting kotlin 0x07:composition
关于Bug处理的一些看法
记录ceph两个rbd删除不了的处理过程
TCP handshake, waving, time wait connection reset and other records
2019年全球移动通信基站市场:爱立信、华为、诺基亚分列前三
[deep learning]: day 9 of pytorch introduction to project practice: dropout implementation (including source code)
【深度学习】:《PyTorch入门到项目实战》第四天:从0到1实现logistic回归(附源码)
Easypoi multi sheet export by template
Call DLL file without source code
College students participated in six Star Education PHP training and found jobs with salaries far higher than those of their peers
Microsoft: edge browser has built-in disk cache compression technology, which can save space and not reduce system performance
SUSE CEPH add nodes, reduce nodes, delete OSD disks and other operations – storage6
Epoll horizontal departure, which edge triggers
Using MVC in the UI of unity
Re10: are we really making much progress? Revisiting, benchmarking, and refining heterogeneous gr
Outline and principle of structured design -- modularization
Understanding of asmlinkage
充分利用----英文