ios - 从通用 MTLBuffer 读取内容?

标签 ios metal mtlbuffer

在我的应用程序中,我有一个 MTLBuffer ,它正在使用通用类型进行实例化。在一种特定情况下,缓冲区将保存与点云中的粒子相关的值,并如此定义;

struct ParticleUniforms {
    simd_float3 position;
    simd_float3 color;
    float confidence;
};

我正在实例化我的MTLBuffer,如下所示;

guard let buffer = device.makeBuffer(length: MemoryLayout<Element>.stride * count, options: options) else {
   fatalError("Failed to create MTLBuffer.")
}

然而,我正在努力的是了解如何读取缓冲区的内容。更重要的是,我希望将缓冲区中每一项的一个元素复制到 CPU 上的一个数组中,稍后我将使用该数组。

实际上,缓冲区保存了ParticleUniforms的集合,我想访问每个项目的position值,将该位置保存到一个单独的数组中。

我在 Stack Overflow 上看到的所有示例似乎都显示 MTLBuffer 保存着浮点集合,尽管我还没有看到任何使用泛型类型的示例。

最佳答案

看来您想要实现的目标只能使用将每个成员保存在连续 block 中的 C 结构来完成(C 结构数组 not 必然是连续的,但 MemoryLayout<Type>.stride 将考虑任何潜在的填充)。 Swift 结构属性 may not be contiguous ,因此以下访问成员值的方法在实际中不起作用。不幸的是,当使用 void* 时你需要知道数据描述的是什么,这并不特别适合 Swift 泛型类型。不过,我会提供一个可能的解决方案。

C 文件:

#ifndef Test_h
#define Test_h

#include <simd/simd.h>

typedef struct {
    vector_float3 testA;
    vector_float3 testB;
} CustomC;

#endif /* Test_h */

Swift 文件(假定桥接 header )

import Metal

// MARK: Convenience
typealias MTLCStructMemberFormat = MTLVertexFormat

@_functionBuilder
struct ArrayLayout { static func buildBlock<T>(_ arr: T...) -> [T] { arr } }

extension MTLCStructMemberFormat {
    var stride: Int {
        switch self {
        case .float2:  return MemoryLayout<simd_float2>.stride
        case .float3:  return MemoryLayout<simd_float3>.stride
        default:       fatalError("Case unaccounted for")
        }
    }
}

// MARK: Custom Protocol
protocol CMetalStruct {
    /// Returns the type of the `ith` member
    static var memoryLayouts: [MTLCStructMemberFormat] { get }
}

// Custom Allocator
class CustomBufferAllocator<Element> where Element: CMetalStruct {
    
    var buffer: MTLBuffer!
    var count: Int
    
    init(bytes: UnsafeMutableRawPointer, count: Int, options: MTLResourceOptions = []) {
        guard let buffer = device.makeBuffer(bytes: bytes, length: count * MemoryLayout<Element>.stride, options: options) else {
            fatalError("Failed to create MTLBuffer.")
        }
        self.buffer = buffer
        self.count = count
    }
    
    func readBufferContents<T>(element_position_in_array n: Int, memberID: Int, expectedType type: T.Type = T.self)
        -> T {
        let pointerAddition = n * MemoryLayout<Element>.stride
            let valueToIncrement = Element.memoryLayouts[0..<memberID].reduce(0) { $0 + $1.stride }
        return buffer.contents().advanced(by: pointerAddition + valueToIncrement).bindMemory(to: T.self, capacity: 1).pointee
    }
    
    func extractMembers<T>(memberID: Int, expectedType type: T.Type = T.self) -> [T] {
        var array: [T] = []
 
        for n in 0..<count {
            let pointerAddition = n * MemoryLayout<Element>.stride
            let valueToIncrement = Element.memoryLayouts[0..<memberID].reduce(0) { $0 + $1.stride }
            let contents = buffer.contents().advanced(by: pointerAddition + valueToIncrement).bindMemory(to: T.self, capacity: 1).pointee
            array.append(contents)
        }
        
        return array
    }
}

// Example

// First extend the custom struct to conform to out type
extension CustomC: CMetalStruct {
    @ArrayLayout static var memoryLayouts: [MTLCStructMemberFormat] {
        MTLCStructMemberFormat.float3
        MTLCStructMemberFormat.float3
    }
}

let device = MTLCreateSystemDefaultDevice()!
var CTypes = [CustomC(testA: .init(59, 99, 0), testB: .init(102, 111, 52)), CustomC(testA: .init(10, 11, 5), testB: .one), CustomC(testA: .zero, testB: .init(5, 5, 5))]

let allocator = CustomBufferAllocator<CustomC>(bytes: &CTypes, count: 3)
let value = allocator.readBufferContents(element_position_in_array: 1, memberID: 0, expectedType: simd_float3.self)
print(value)

// Prints SIMD3<Float>(10.0, 11.0, 5.0)

let group = allocator.extractMembers(memberID: 1, expectedType: simd_float3.self)
print(group)

// Prints [SIMD3<Float>(102.0, 111.0, 52.0), SIMD3<Float>(1.0, 1.0, 1.0), SIMD3<Float>(5.0, 5.0, 5.0)]

这类似于 MTLVertexDescriptor ,除非内存是手动访问的,而不是通过[[stage_in]]属性和参数表传递给片段着色器顶点的每个实例。您甚至可以扩展分配器以接受带有属性名称的字符串参数,并保存一些映射到成员 ID 的字典。

关于ios - 从通用 MTLBuffer 读取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63606753/

相关文章:

objective-c - Objective-C - block 代码不按顺序执行?

objective-c - 何时使用多个 MTLRenderCommandEncoders 来执行我的 Metal 渲染?

Swift Metal 将 bgra8Unorm 纹理保存到 PNG 文件

ios - Metal 片段着色器获取大小

ios - 创建后更改 MTLBuffer 的值

ios - 绘制 MTLBuffer 的一部分?

iphone - 将时间替换为另一个 NSDate 的时间?

ios - 如何从标签栏快速深层链接

ios - 当表格 View 有两个部分时,如何知道哪一行被选中?