c1_unity/Assets/Scripts/Component/PostEffect/PostEffectVividBloom.cs
2023-04-03 11:04:31 +08:00

125 lines
3.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BF
{
public class PostEffectVividBloom : AbsPostEffect
{
public static int FilterID = Shader.PropertyToID("_Filter");
public static int IntensityID = Shader.PropertyToID("_Intensity");
public static int SourceTexID = Shader.PropertyToID("_SourceTex");
const int BoxDownPrefilterPass = 0;
const int BoxDownPass = 1;
const int BoxUpPass = 2;
const int ApplyBloomPass = 3;
Material vividBloomMat;
RenderTexture[] textures = new RenderTexture[4];
[Range(0, 3)]
float intensity = 1;
[Range(1, 4)]
int iterations = 3;
[Range(0, 10)]
float threshold = 1;
[Range(0, 1)]
float softThreshold = 0.5f;
public float Intensity { get { return intensity; } }
public int Iterations { get { return iterations; } }
public float Threshold { get { return threshold; } }
public float SoftThreshold { get { return softThreshold; } }
public void SetIntensity(float value)
{
intensity = value;
RefreshIntensity();
}
public void SetIterations(int value)
{
iterations = value;
}
public void SetThreshold(float value)
{
threshold = value;
RefreshFilter();
}
public void SetSoftThreshold(float value)
{
softThreshold = value;
RefreshFilter();
}
public PostEffectVividBloom()
{
vividBloomMat = BFMain.Instance.RenderMgr.VividBloomMat;
RefreshFilter();
RefreshIntensity();
}
public void RefreshFilter()
{
var knee = threshold * softThreshold;
Vector4 filter;
filter.x = threshold;
filter.y = filter.x - knee;
filter.z = 2f * knee;
filter.w = 0.25f / (knee + 0.00001f);
vividBloomMat.SetVector(FilterID, filter);
}
public void RefreshIntensity()
{
vividBloomMat.SetFloat(IntensityID, intensity);
}
public override PostEffectContext OnRenderImage(PostEffectContext context)
{
var src = context.src;
var dest = context.dest;
int width = src.width / 2;
int height = src.height / 2;
var format = src.format;
var currentDestination = textures[0] = RenderTexture.GetTemporary(width, height, 0, format);
Graphics.Blit(src, currentDestination, vividBloomMat, BoxDownPrefilterPass);
var currentSource = currentDestination;
int i = 1;
for (; i < iterations; i++)
{
width /= 2;
height /= 2;
if (height < 2)
{
break;
}
currentDestination = textures[i] = RenderTexture.GetTemporary(width, height, 0, format);
Graphics.Blit(currentSource, currentDestination, vividBloomMat, BoxDownPass);
currentSource = currentDestination;
}
for (i -= 2; i >= 0; i--)
{
currentDestination = textures[i];
textures[i] = null;
Graphics.Blit(currentSource, currentDestination, vividBloomMat, BoxUpPass);
RenderTexture.ReleaseTemporary(currentSource);
currentSource = currentDestination;
}
vividBloomMat.SetTexture(SourceTexID, src);
Graphics.Blit(currentSource, dest, vividBloomMat, ApplyBloomPass);
RenderTexture.ReleaseTemporary(currentSource);
return context;
}
}
}