Unity Computer shader后效

使用范围:像素处理、粒子效果、大规模同步无依赖运算。
1\检测是否支持:
SystemInfo.supportsComputeShaders

2\创建Computer Shader
click>Create>Shader>Compute Shader

直接上代码

using UnityEngine;

public class CBW : MonoBehaviour
{
    public ComputeShader shader;
    public Camera cam;
    public RenderTexture rt;

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if(rt == null)
        {
            RenderTexture camTex = cam.activeTexture;
            if (camTex == null) return;
            rt = new RenderTexture(camTex.descriptor);
            rt.enableRandomWrite = true;
            rt.Create();
        }

        if (shader == null|| rt == null) return;

        Graphics.Blit(source, rt);
        int kernel = shader.FindKernel("CSMain");
        uint shaderThreadX, shaderThreadY, shaderThreadZ;
        shader.GetKernelThreadGroupSizes(kernel,out shaderThreadX,out shaderThreadY,out shaderThreadZ);

        int dispathXF = Mathf.CeilToInt(source.width / shaderThreadX)+1;
        int dispathYF = Mathf.CeilToInt(source.height / shaderThreadY)+1;

        shader.SetTexture(kernel, "InOutputTexture", rt);    
        shader.Dispatch(kernel,dispathXF,dispathYF,1);

        Graphics.Blit(rt,destination);
    }
}

Computer Shader

// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain

// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
RWTexture2D<float4> InOutputTexture;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    // TODO: insert actual code here!
    float4 color = InOutputTexture[id.xy];

    //Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0);
    float c = color.r * 0.30 + color.g * 0.59 + color.b * 0.11;
    InOutputTexture[id.xy] = float4(c, c, c,color.a);

}

说明:
使用默认管线,如果是URP管线,需要使用Feature进行操作

使用Computer shader 前后

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值