Unity5 Compute && Geometry Shader

Compute Shader

Compute Shader技术是微软DirectX 11 API新加入的特性,在Compute Shader的帮助下,我们可以直接利用GPU的并行运算能力进行大量数据的运算,达到减轻CPU负荷的目的。Compute Shader可以应用在如粒子效果、碰撞检测、水面效果等情景,也能用来对画面进行后期处理。

Unity已经对Compute Shader做了相应支持。我们可以通过Create->Shader->Compute 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> Result;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    // TODO: insert actual code here!

    Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0);
}

这里我们定义了一个Kernel函数(CSMain),并通过[numthreads(thread_group_size_x, thread_group_size_y, thread_group_size_z)]设定了一个thread group中的线程数。需要注意的是一个thread group中的线程数不能超过1024。

在C#脚本中,我们通过以下代码来运行Compute Shader中的kernel函数:

ComputeShader cs;

int CSKernel = cs.FindKernel("CSMain");
cs.SetTexture("Result", renderTexture);
cs.Dispatch(CSKernel, threadGroupsX, threadGroupsY, threadGroupsZ);

以上脚本的运行结果,将产生theadGroupsX * threadGroupsY * threadGroupsZ个thread group,这样,一次运行产生的线程总数为theadGroupsX * threadGroupsY * threadGroupsZ * thread_group_size_x * thread_group_size_y * thread_group_size_z,如果这些值都为10,那么线程总数是100万,这是一个相当惊人的数字。

Kernel函数的参数可以是SV_GroupID, SV_GroupThreadID, SV_DispatchThreadID, SV_GroupIndex这几个系统变量的组合。我们可以通过例子来了解这几个变量的关系:

这里写图片描述

我们可以把SV_GroupIndex看作线程在其所在thread group中的次序:

SV_GroupIndex = SV_GroupThreadID.x + SV_GroupThreadID.y * thread_group_size_x + SV_GroupThreadID.z * thread_group_size_x * thread_group_size_y;

另一个比较常用的是线程在整个Dispatch中的次序,我们可以将其作为Compute Shader绑定的数组的脚标,假设SV_DispatchThreadID为id:

uint idx = id.x + id.y * thread_group_size * threadGroupsX + id.z * thread_group_size_x * threadGroupsX * thread_group_size_y * threadGroupsY;

Geometry Shader

Compute Shader只能用来计算,不能用来渲染,当我们想要实现粒子效果时,可以通过Compute Shader来计算每个粒子的位置,但是要将其渲染出来,还需要借助Vertex Shader或Geometry Shader。

Geometry Shader在Rendering Pipeline中排在Vertex Shader之后,它接受Vertex Shader的返回值,根据MeshTopology生成几何构造(Points、Lines、Triangles等),并将其交给后面的Shader(通常是Fragment Shader)处理。

示例

本文所附的工程中包含了Compute Shader和Geometry Shader应用的几个例子:

结合Perline Noise生成随机地图:
Perline Noise Map

雨雪天气效果:
Weather

鼠标跟随的例子效果(100万个点):
ParticleFollow

例子在这里–>GitHub

参考Compute And Geometry Shader Tutorial

猜你喜欢

转载自blog.csdn.net/winchyy/article/details/53035681