用作索引的强制转换变量(金属着色语言)



我正在尝试使用浮点变量作为索引来访问MTLBuffer的位置,但我必须将其转换为无符号int。嗯,这是我的第一个想法。

在实践中,这似乎不起作用,但我不太明白为什么。

我基本上有这样的东西:

vertex VertexOut basic_vertex(const device float3 *vertex_array   [[ buffer(0) ]],
                              const device float3 *color_array    [[ buffer(1) ]], 
(...))
{
   // get the current vertex
   float3 position = vertex_array[vid];
   // get the color index
   uint color_index = as_type<uint>(position.z);
   // get the color
   float3 color = color_array[color_index];
   VertexOut vertexOut;
   vertexOut.position = proj_Matrix * mv_Matrix * float4(position.x, position.y, 0, 1);
   vertexOut.color = float4(color, 1);
   return vertexOut;
}

我正在尝试通过使用 Z 坐标为颜色缓冲区编制索引来减少要发送到 GPU 的数据量,而不是对大量顶点重复相同的颜色。这样,我只需要通过 3 个加上颜色,而不是通过 6 个浮点数 (x,y,z,r,g,b(。

我得到的错误不是当我使用 color_index 变量来获取颜色时。问题是当我尝试访问颜色时,例如:

vertexOut.color = float4(color, 1);

如果我这样做,我会得到这个错误:

Execution of the command buffer was aborted due to an error during execution. Caused GPU Hang Error (IOAF code 3)

对于我想要完成的任务,是否有任何解决方法?我在这里做错了什么?

提前谢谢你

as_type

功能上等同于C++的reinterpret_cast:它从字面上将源值的位视为提供的类型,这在这种情况下是不正确的。你可能想要的是类似于floor的东西,或者根本没有强制转换(即你可以用float初始化索引,并且(昂贵的(floatuint的转换将隐式发生(。在未访问颜色时没有收到此错误的事实可能表明,当结果值未使用时,数组访问正在消除死代码。

最新更新