Last active
July 21, 2023 08:53
-
-
Save wakita/f4915757c6c6c128c05c8680cd859e1a to your computer and use it in GitHub Desktop.
Metal compute shader example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MetalKit | |
let device = MTLCreateSystemDefaultDevice()! | |
let commandQueue = device.makeCommandQueue()! | |
let library = try device.makeLibrary(filepath: "compute.metallib") | |
let commandBuffer = commandQueue.makeCommandBuffer()! | |
let encoder = commandBuffer.makeComputeCommandEncoder()! | |
encoder.setComputePipelineState(try device.makeComputePipelineState(function: library.makeFunction(name: "add")!)) | |
let input: [Float] = [1.0, 2.0] | |
encoder.setBuffer(device.makeBuffer(bytes: input as [Float], length: MemoryLayout<Float>.stride * input.count, options: []), | |
offset: 0, index: 0) | |
let outputBuffer = device.makeBuffer(length: MemoryLayout<Float>.stride, options: [])! | |
encoder.setBuffer(outputBuffer, offset: 0, index: 1) | |
let numThreadgroups = MTLSize(width: 1, height: 1, depth: 1) | |
let threadsPerThreadgroup = MTLSize(width: 1, height: 1, depth: 1) | |
encoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerThreadgroup) | |
encoder.endEncoding() | |
commandBuffer.commit() | |
commandBuffer.waitUntilCompleted() | |
let result = outputBuffer.contents().load(as: Float.self) | |
print(String(format: "%f + %f = %f", input[0], input[1], result)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SDK = xcrun -sdk macosx | |
all: compute.metallib compute | |
compute.metallib: Compute.metal | |
# Metal intermediate representation (.air) | |
$(SDK) metal -c -Wall -Wextra -std=osx-metal2.0 -o /tmp/Compute.air $^ | |
# Metal library (.metallib) | |
$(SDK) metallib -o $@ /tmp/Compute.air | |
compute: compute.swift | |
$(SDK) swiftc -o $@ $^ | |
clean: | |
rm -f compute.metallib compute |
hi @rasky, i am chasing the same bug with a different metal library, did you find the cause to this "IsValidCurbeEntry" bug?
thanks
Ricardo
No sorry @rcorin
Thanks a lot, official Apple documentation lacks Swift examples.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, trying to compile and run this, I get a binary that segfaults:
Any idea? I'm running Mojave 10.14.6 with Xcode 11.3.1.