当前位置:网站首页>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"
}
边栏推荐
- 传英伟达已与软银展开会谈,将出价超过320亿美元收购Arm
- 【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
- Binary representation of negative integers and floating point numbers
- Unity editor learning (I) using features to change the display of fields in components
- kubenertes 1.16集群部署问题总结
- Do you really understand CMS garbage collector?
- [deep learning]: day 9 of pytorch introduction to project practice: dropout implementation (including source code)
- Create a self-organizing / safe / controllable Lora network! Semtech responded for the first time to the impact of the "new regulations of the Ministry of industry and information technology"
- Add differential pairs and connections in Ad
- mysql 最大建议行数2000w,靠谱吗?
猜你喜欢

Brother Ali teaches you how to correctly understand the problem of standard IO buffer

Easypoi multi sheet export by template

College students participated in six Star Education PHP training and found jobs with salaries far higher than those of their peers
![[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)

浏览器解码过程分析

Interesting kotlin 0x06:list minus list

Text filtering skills

HTAP是有代价的
![[deep learning]: day 5 of pytorch introduction to project practice: realize softmax regression from 0 to 1 (including source code)](/img/19/18d6e94a1e0fa4a75b66cf8cd99595.png)
[deep learning]: day 5 of pytorch introduction to project practice: realize softmax regression from 0 to 1 (including source code)

Jsonarray traversal
随机推荐
打造自组/安全/可控的LoRa网!Semtech首度回应“工信部新规”影响
How to use fail2ban to protect WordPress login page
2019年全球移动通信基站市场:爱立信、华为、诺基亚分列前三
Cluster construction and use of redis5
Re13:读论文 Gender and Racial Stereotype Detection in Legal Opinion Word Embeddings
SUSE CEPH rapid deployment – storage6
parseJson
概率论与数理统计第一章
SUSE CEPH add nodes, reduce nodes, delete OSD disks and other operations – storage6
Binary representation of negative integers and floating point numbers
Unity shader transparent effect
MD5 encryption verification
Read excel xlsx format file in unity
Egg (19): use egg redis performance optimization to cache data and improve response efficiency
Interesting kotlin 0x06:list minus list
Implementation of transfer business
Unity3d shader achieves ablation effect
Is smart park the trend of future development?
Semtech推出物联网地理定位解决方案LoRa Edge,首款芯片LR1110现已上市
Some notes on how unity objects move