Skip to content

Instantly share code, notes, and snippets.

@randomsequence
Last active June 12, 2020 11:38
Show Gist options
  • Save randomsequence/a82bef8ee6d34743027fbe6589f1f1e2 to your computer and use it in GitHub Desktop.
Save randomsequence/a82bef8ee6d34743027fbe6589f1f1e2 to your computer and use it in GitHub Desktop.
Use BlitCommandEncoder to sync destination
import MetalPerformanceShaders
struct Pixel {
var red: UInt8
var green: UInt8
var blue: UInt8
var alpha: UInt8
}
let count = 64
let bytesPerRow = MemoryLayout<Pixel>.size * count
let device = MTLCreateSystemDefaultDevice()!
let queue = device.makeCommandQueue()!
let commands = queue.makeCommandBuffer()!
let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: count, height: 1, mipmapped: false)
let source = device.makeTexture(descriptor: descriptor)!
let destination = device.makeTexture(descriptor: descriptor)!
let region = MTLRegionMake2D(0, 0, count, 1)
var array = [Pixel](repeating: Pixel(red: 128, green: 128, blue: 128, alpha: 128), count: count)
array.withUnsafeBytes { ptr in
source.replace(region: region, mipmapLevel: 0, withBytes: ptr.baseAddress!, bytesPerRow: bytesPerRow)
}
let conversion = MPSImageConversion(device: device, srcAlpha: .nonPremultiplied, destAlpha: .premultiplied, backgroundColor: nil, conversionInfo: nil)
conversion.encode(commandBuffer: commands, sourceTexture: source, destinationTexture: destination)
commands.commit()
let blitCommands = queue.makeCommandBuffer()!
let blit = blitCommands.makeBlitCommandEncoder()!
blit.synchronize(resource: destination)
blit.endEncoding()
blitCommands.commit()
blitCommands.waitUntilCompleted()
var converted = [Pixel](repeating: Pixel(red: 1, green: 2, blue: 3, alpha: 4), count: count)
converted.withUnsafeMutableBytes { ptr in
destination.getBytes(ptr.baseAddress!, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
}
// expected: Pixel(red: 64, green: 64, blue: 64, alpha: 128)
// actual: Pixel(red: 128, green: 128, blue: 128, alpha: 128)
print(converted[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment