Unity计算缓冲区,用于跟踪纹理中的颜色量



我一直在尝试制作一个计算缓冲区,用于跟踪创建程序岛纹理的着色器中具有特定颜色的像素数量。

这是我的计算着色器:的简化版本

#pragma kernel CSMain
RWTexture2D<float4> Result;
RWStructuredBuffer<int> Biomes; // This buffer
float2 WorldSize;
float IslandSize;
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
float2 position = float2(id.x - WorldSize.x, id.y - WorldSize.y);
float3 color = float3(0, 0, 1);
float2 noise = generateNoise(position / IslandSize * 1000);
float height = noise.x * 100;
float falloff = noise.y;
if (falloff < 1 && height < 5)
{
color = float3(0, 0.1, 1);
InterlockedAdd(Biomes[1], 1); // Data gets added to the buffer
}

Result[id.xy] = float4(color, 1);
}

这是我的简化C#代码(biomes是纹理中具有特定颜色的像素数的列表(,它是从OnGUI():调用的函数的一部分

// Set shader parameters
TerrainShader.SetVector("WorldSize", new Vector2(xSize, zSize));
TerrainShader.SetFloat("IslandSize", IslandSize * SizeMultiplier);
biomesBuffer = new ComputeBuffer(7, sizeof(int) * 7); // Buffer initialization
TerrainShader.SetBuffer(0, "Biomes", biomesBuffer);
// Dispatch compute shader
TerrainShader.SetTexture(0, "Result", target);
TerrainShader.Dispatch(0, xSize * 2, zSize * 2, 1);
// Get biome data
int[] biomes = new int[7];
biomesBuffer.GetData(biomes); // Retrieving data from buffer
string log = "";
for (int i = 0; i < biomes.Length; i++) {
log += $"Biome {i}: {biomes[i]} ";
}
Debug.Log(log);
biomesBuffer.Dispose();

这就是我的控制台的样子:

Biome 0: 2030086002 Biome 1: 0 Biome 2: 19020880 Biome 3: 52763400 Biome 4: 24948620 Biome 5: 16871260 Biome 6: 15926730
Biome 0: 1462274385 Biome 1: 0 Biome 2: 53590760 Biome 3: 148659300 Biome 4: 70291988 Biome 5: 47534272 Biome 6: 44873085
Biome 0: 843603332 Biome 1: 522 Biome 2: 37425056 Biome 3: 103816080 Biome 4: 49088343 Biome 5: 33195513 Biome 6: 31337076
Biome 0: 2030086002 Biome 1: 0 Biome 2: 19020880 Biome 3: 52763400 Biome 4: 24948620 Biome 5: 16871260 Biome 6: 15926730
Biome 0: 1462274385 Biome 1: 0 Biome 2: 53590760 Biome 3: 148659300 Biome 4: 70291988 Biome 5: 47534272 Biome 6: 44873085
...

我是一个计算着色器的新手,不知道这些数字是从哪里来的。它们在控制台的每一行中都应该是相同的,因为纹理保持不变。

以下是纹理的外观,供参考:计算着色器结果

我可能错了,但我相信你的代码应该能工作,除了你只设置为Biome[1]这一事实之外——你得到的其他数字都是来自内存的随机未设置位。

最新更新