如何正确创建自定义空纹理?

How to create custom empty Texture correctly?

我需要用我的自定义数据(当前填充为 0)创建一个 MTLTexture,为此我使用了这样的实现

  private func createTexture(frame: UnsafeMutableRawPointer) -> MTLTexture? {
    let width = 2048
    let height = 2048
    
    let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(
      pixelFormat: MTLPixelFormat.rgba8Unorm,
      width: width,
      height: height,
      mipmapped: false)
    
    textureDescriptor.usage = [.shaderWrite, .shaderRead]
    
    guard let texture: MTLTexture = device?.makeTexture(descriptor: textureDescriptor) else
    {
      logger?.log(severity: .error, msg: "create texture FAILED.")
      return nil
    }
    
    let region = MTLRegion.init(origin: MTLOrigin.init(x: 0, y: 0, z: 0), size: MTLSize.init(width: texture.width, height: texture.height, depth: 4));
    
    //MARK: >>> JUST FOR TEST
    let count = width * height * 4
    let stride = MemoryLayout<CChar>.stride
    let alignment = MemoryLayout<CChar>.alignment
    let byteCount = stride * count
    
    let p = UnsafeMutableRawPointer.allocate(byteCount: byteCount, alignment: alignment)
    let data = p.initializeMemory(as: CChar.self, repeating: 0, count: count)
    //MARK: <<<
      
    texture.replace(region: region, mipmapLevel: 0, withBytes: data, bytesPerRow: width * 4)
    
    return texture
  }

所以,我在这里创建了一个具有 4 个通道的描述符,然后我创建了一个 depth: 4 的区域,然后创建了 UnsafeMutableRawPointer 并填充了 stride * count 大小的数据,但是我得到了一个错误在这一行

texture.replace(region: region, mipmapLevel: 0, withBytes: data, bytesPerRow: width * 4)

_validateReplaceRegion:155: failed assertion `(origin.z + size.depth)(4) must be <= depth(1).'

我做错了什么?

下一行中的深度 属性 不正确:

let region = MTLRegion.init(origin: MTLOrigin.init(x: 0, y: 0, z: 0), size: MTLSize.init(width: texture.width, height: texture.height, depth: 4));

深度属性描述了z维度中元素的数量。对于 2D 纹理,它应该是 1.