我有一个浮点值数组,代表我最终想要渲染为MTLView
. 这是在 macOS 上,但我希望能够在某个时候将其应用于 iOS。我最初用数据创建一个MTLBuffer
:
NSData *floatData = ...;
id<MTLBuffer> metalBuffer = [device newBufferWithBytes:floatData.bytes
length:floatData.length
options:MTLResourceCPUCacheModeDefaultCache | MTLResourceStorageModeManaged];
从这里开始,我通过几个计算管道运行缓冲区。接下来,我想创建一个 RGBMTLTexture
对象以传递给几个CIFilter
/MPS 过滤器,然后显示。创建一个使用已经创建的缓冲区作为支持以避免制作另一个副本的纹理似乎是有意义的。(我已经成功地使用了像素格式的纹理MTLPixelFormatR32Float
。)
// create texture with scaled buffer - this is a wrapper, i.e. it shares memory with the buffer
MTLTextureDescriptor *desc;
desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float
width:width
height:height
mipmapped:NO];
desc.usage = MTLResourceUsageRead;
desc.storageMode = scaledBuffer.storageMode; // must match buffer
id<MTLTexture> scaledTexture = [scaledBuffer newTextureWithDescriptor:desc
offset:0
bytesPerRow:imageWidth * sizeof(float)];
图像尺寸为 242x242。当我运行它时,我得到:
validateNewTexture:89: failed assertion `BytesPerRow of a buffer-backed
texture with pixelFormat(MTLPixelFormatR32Float) must be aligned to 256 bytes,
found bytesPerRow(968)'
我知道我需要使用:
NSUInteger alignmentBytes = [self.device minimumLinearTextureAlignmentForPixelFormat:MTLPixelFormatR32Float];
如何定义缓冲区以使字节正确对齐?
更一般地说,这是处理这类数据的合适方法吗?这是我有效地将浮点数据转换为有颜色的东西的阶段。为了澄清,这是我的下一步:
// render into RGB texture
MPSImageConversion *imageConversion = [[MPSImageConversion alloc] initWithDevice:self.device
srcAlpha:MPSAlphaTypeAlphaIsOne
destAlpha:MPSAlphaTypeAlphaIsOne
backgroundColor:nil
conversionInfo:NULL];
[imageConversion encodeToCommandBuffer:commandBuffer
sourceImage:scaledTexture
destinationImage:intermediateRGBTexture];
其中intermediateRGBTexture
是定义MTLPixelFormatRGBA16Float
为利用 EDR 的 2D 纹理。