Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop and scale MTLTexture

Tags:

ios

metal

Can I create a new MTLTexture of dimensions w2/h2 of an existing MTLTexture region x1/y1/w1/h1?

PS: I thought about using MTLTexture.buffer?.makeTexture but the offset needs to be 64 bytes. Why?

like image 449
Era Avatar asked Dec 05 '16 09:12

Era


2 Answers

Here's an example of how you might do this with MPSImageLanczosScale. Note that sourceRegion is expressed in the pixel coordinate system of the source texture, and destRegion should be equal to the full area of the destination texture (note that it specifically doesn't account for the origin of the destination region):

let scaleX = Double(destRegion.size.width) / Double(sourceRegion.size.width)
let scaleY = Double(destRegion.size.height) / Double(sourceRegion.size.height)
let translateX = Double(-sourceRegion.origin.x) * scaleX
let translateY = Double(-sourceRegion.origin.y) * scaleY
let filter = MPSImageLanczosScale(device: device)
var transform = MPSScaleTransform(scaleX: scaleX, scaleY: scaleY, translateX: translateX, translateY: translateY)
let commandBuffer = commandQueue.makeCommandBuffer()
withUnsafePointer(to: &transform) { (transformPtr: UnsafePointer<MPSScaleTransform>) -> () in
    filter.scaleTransform = transformPtr
    filter.encode(commandBuffer: commandBuffer, sourceTexture: sourceTexture, destinationTexture: destTexture)
}
commandBuffer.commit()
commandBuffer.waitUntilCompleted()

If you need to read the destination texture on the CPU, you can wait until the command buffer completes, or add a completed handler to the command buffer to receive an async callback when the resampling work is done. Otherwise, you can encode additional work in the command buffer and use the destination texture immediately. If you're going to be repeatedly scaling textures, you should keep a single instance of MPSImageLanczosScale around instead of repeatedly creating instances of it.

like image 78
warrenm Avatar answered Nov 04 '22 16:11

warrenm


MPSImageScale can't be used directly because it is an abstract class. The concrete classes are MPSImageLanczosScale and MPSImageBilinearScale.

like image 22
Sebastian Avatar answered Nov 04 '22 16:11

Sebastian