ios - Metal 渲染真的很慢 - 如何加快速度

标签 ios metal

我有一个运行速度非常慢的 Metal 应用程序,需要运行得更快。我相信问题是我创建了太多 MTLCommandBuffer 对象。

我创建这么多 MTLCommandBuffer 对象的原因是我需要向像素着色器发送不同的统一值。我粘贴了一段代码来说明下面的问题。

  for (int obj_i = 0 ; obj_i < n ; ++obj_i)
  {
     // I create one render command buffer per object I draw so I can use  different uniforms
     id <MTLCommandBuffer> mtlCommandBuffer = [metal_info.g_commandQueue commandBuffer];
     id <MTLRenderCommandEncoder> renderCommand = [mtlCommandBuffer renderCommandEncoderWithDescriptor:<#(MTLRenderPassDescriptor *)#>]

     // glossing over details, but this call has per object specific data
     memcpy([global_uniform_buffer contents], per_object_data, sizeof(per_data_object));

     [renderCommand setVertexBuffer:object_vertices  offset:0 atIndex:0];
     // I am reusing a single buffer for all shader calls
     // this is killing performance
     [renderCommand setVertexBuffer:global_uniform_buffer offset:0 atIndex:1];

     [renderCommand drawIndexedPrimitives:MTLPrimitiveTypeTriangle
                               indexCount:per_object_index_count
                               indexType:MTLIndexTypeUInt32
                             indexBuffer:indicies
                       indexBufferOffset:0];
     [renderCommand endEncoding];
     [mtlCommandBuffer presentDrawable:frameDrawable];
     [mtlCommandBuffer commit];
}  

上面的代码按预期绘制,但是非常慢。我猜是因为有一种比为每个对象创建 MTLCommandBuffer 更好的方法来强制像素着色器评估。

我考虑过简单地分配一个比单个着色器 channel 所需的缓冲区大得多的缓冲区,并简单地使用偏移量在一个渲染命令编码器中排队多个调用,然后执行它们。这种方法看起来很不正统,我想确保我正在解决以 Metal 友好的方式为每个对象发送自定义数据所需的问题。

使用每次调用自定义统一数据对同一像素/顶点着色器进行多次渲染的最快渲染方式是什么?

最佳答案

不要为每个对象重复使用相同的统一缓冲区。这样做会破坏 CPU 和 GPU 之间的所有并行性并导致正常的同步点。

相反,为您要在帧中渲染的每个对象创建一个单独的统一缓冲区。事实上,您真的应该为每个对象创建 2 个对象,并在每帧之间交替,这样 GPU 就可以渲染最后一帧,而您正在 CPU 上准备下一帧。

在你这样做之后,你只需重构你的循环,这样命令缓冲区和渲染命令工作每帧完成一次。您的循环应该只包括复制统一数据、设置顶点缓冲区和调用绘图原语。

关于ios - Metal 渲染真的很慢 - 如何加快速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30087187/

相关文章:

ios - 通知横幅样式 iOS

android - 使用 Linux 和命令行将 Android PhoneGap 应用程序转换为 iOS

rendering - 使用 Apple 的 Metal 渲染第二个顶点缓冲区

ios - Swift 数组访问器比原生数组慢 5 倍——哪些是推荐的?

random - 如何在 Metal 着色器中获取随机数?

objective-c - 将 Xcode MacOS 游戏模板移植到 СMake 时出现问题

ios - Objective-c:从具有范围的集合(NSArray)中获取最短范围的最有效方法

ios - 带有 "+"文本的 UILabel 未垂直居中

ios - 从 PHAsset 中提取元数据返回意外的 nil 值

ios - 在 Metal 中填充 float 缓冲区