Home > Software design >  Is it possible to initialize a Metal array texture all at once?
Is it possible to initialize a Metal array texture all at once?

Time:10-25

An array texture (not to be confused with texture array) in Metal can be used to pass a non compile time constant number of textures of the same dimensions to the GPU at the same time. So far, the only way I know of to create these is with a custom MTLTextureDescriptor and then copying the data manually. Currently I use a for loop to copy one slice at a time:

let descriptor = MTLTextureDescriptor()
descriptor.width = 32
descriptor.height = 32
descriptor.mipmapLevelCount = 5
descriptor.storageMode = .private
descriptor.textureType = .type2DArray
descriptor.pixelFormat = .rgba8Unorm
descriptor.arrayLength = NUM_TEXTURES
if let texture = device.makeTexture(descriptor: descriptor) {
    for i in 0..<NUM_TEXTURES {
        commandEncoder.copy(from: sharedBufferWithTextureData, sourceOffset: i<<4096, sourceBytesPerRow: 128, sourceBytesPerImage: 4096, to: texture, destinationSlice: i, destinationLevel: 0, destinationOrigin: MTLOrigin())
    }
}
commandEncoder.generateMipmaps(for: texture)

However, is there a way to copy all the slices at once? OpenGL seems to provide a way to do this, but how can I do this in Metal? What is the best way to create a MTLTexture object where textureType is type2DArray and storageMode is private then populate the texture data?

Note: The storageMode is private because MTLTexture does not support shared, and managed results in separate copies of the data, which is unnecessary memory usage.

CodePudding user response:

There is no way to populate more than one slice in single blit command, as there is no copy() method that can handle more than one slice at a time.

It is also not possible to create a buffer with the slice data and create a texture that shares the memory of the buffer using MTLBuffer.makeTexture() as this function explicitly disallows use with array textures.

The only way to copy 'multiple' textures worth of texture data at once is to combine multiple textures into a single one, for example, by using a texture atlas.

  • Related