Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MasDennis/f7410569185dacb65d6ccfe1542ff1e3 to your computer and use it in GitHub Desktop.
Save MasDennis/f7410569185dacb65d6ccfe1542ff1e3 to your computer and use it in GitHub Desktop.
func setupMetalResources() {
guard let device = scnView.device else {
assertionFailure()
return
}
// We're drawing a simple triangle so we only need a position and a color
struct TriangleVertex {
var position: vector_float4
var color: vector_float4
}
// Define the triangle's vertices and colors
let vertices: [TriangleVertex] = [
// Top triangle, red color
TriangleVertex(position: vector_float4( 0.0, 0.5, 0, 1), color: vector_float4(1, 0, 0, 1)),
// Bottom left triangle, green color
TriangleVertex(position: vector_float4( -0.5, -0.5, 0, 1), color: vector_float4(0, 1, 0, 1)),
// Bottom right triangle, blue color
TriangleVertex(position: vector_float4( 0.5, -0.5, 0, 1), color: vector_float4(0, 0, 1, 1))
]
// Create the vertex buffer
self.vertexBuffer = device.makeBuffer(
bytes: vertices,
length: MemoryLayout<TriangleVertex>.size * vertices.count,
options: .cpuCacheModeWriteCombined)
// Set up the shaders
let library = device.makeDefaultLibrary()
let vertexFunc = library?.makeFunction(name: "passthrough_vertex")
let fragmentFunc = library?.makeFunction(name: "passthrough_fragment")
// Create the pipeline descriptor
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunc
pipelineDescriptor.fragmentFunction = fragmentFunc
// Use SCNView's pixel format
pipelineDescriptor.colorAttachments[0].pixelFormat = scnView.colorPixelFormat
pipelineDescriptor.depthAttachmentPixelFormat = scnView.depthPixelFormat
guard let pipeline = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)
else {
assertionFailure()
return
}
self.pipelineState = pipeline
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment