MPSImageIntegral 返回全零

MPSImageIntegral returning all zeros

我正在尝试使用 MPSImageIntegral 来计算 MTLTexture 中某些元素的总和。这就是我正在做的事情:

std::vector<float> integralSumData;
for(int i = 0; i < 10; i++)
    integralSumData.push_back((float)i);

MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float
                                                                                             width:(integralSumData.size()) height:1 mipmapped:NO];
textureDescriptor.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
id<MTLTexture> texture = [_device newTextureWithDescriptor:textureDescriptor];

// Calculate the number of bytes per row in the image.
NSUInteger bytesPerRow = integralSumData.size() * sizeof(float);

MTLRegion region =
{
    { 0, 0, 0 },                   // MTLOrigin
    {integralSumData.size(), 1, 1} // MTLSize
};

// Copy the bytes from the data object into the texture
[texture replaceRegion:region
           mipmapLevel:0
             withBytes:integralSumData.data()
           bytesPerRow:bytesPerRow];


MTLTextureDescriptor *textureDescriptor2 = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float
                                                                                              width:(integralSumData.size()) height:1 mipmapped:NO];
textureDescriptor2.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
id<MTLTexture> outtexture = [_device newTextureWithDescriptor:textureDescriptor2];


// Create a MPS filter.
MPSImageIntegral *integral = [[MPSImageIntegral alloc] initWithDevice: _device];
MPSOffset offset = { 0,0,0};
[integral setOffset:offset];
[integral setEdgeMode:MPSImageEdgeModeZero];
[integral encodeToCommandBuffer:commandBuffer sourceTexture:texture destinationTexture:outtexture];

[commandBuffer commit];
[commandBuffer waitUntilCompleted];

但是,当我检查我的 outtexture 值时,它全为零。难道我做错了什么?这是我使用 MPSImageIntegral 的正确方法吗?

我正在使用以下代码读取写入 outTexture 的值:

float outData[100];
[outtexture getBytes:outData bytesPerRow:bytesPerRow fromRegion:region mipmapLevel:0];
for(int i = 0; i < 100; i++)
    std::cout << outData[i] << "\n";

谢谢

正如@Matthijis 所指出的那样:我所要做的就是使用 MTLBlitEncoder 来确保在将 MTLTexture 读入 CPU 之前同步它,它的工作方式就像魅力!