1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
import MetalKit
enum Colors { static let wenderlichGreen = MTLClearColor(red: 0.0, green: 0.4, blue: 0.21, alpha: 1.0) }
class Renderer: NSObject { let device: MTLDevice let commandQueue: MTLCommandQueue var vertices: [Float] = [ -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0, ] let indices: [UInt16] = [ 0, 1, 2, 2, 3, 0 ] var pipelineState: MTLRenderPipelineState? var vertexBuffer: MTLBuffer? var indexBuffer: MTLBuffer?
struct Constants { var animateBy: Float = 0 } var constants = Constants() var time: Float = 0
init(device: MTLDevice) { self.device = device commandQueue = device.makeCommandQueue()! super.init() buildModel() buildPipelineState() }
private func buildModel() { vertexBuffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<Float>.size, options: []) indexBuffer = device.makeBuffer(bytes: indices, length: indices.count * MemoryLayout<UInt16>.size, options: []) }
private func buildPipelineState() { let library = device.makeDefaultLibrary() let vertexFunction = library?.makeFunction(name: "vertex_shader") let fragmentFunction = library?.makeFunction(name: "fragment_shader")
let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = vertexFunction pipelineDescriptor.fragmentFunction = fragmentFunction pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
do { pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor) } catch let error as NSError { print("error: \(error.localizedDescription)") } } }
extension Renderer: MTKViewDelegate { func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } func draw(in view: MTKView) { guard let drawable = view.currentDrawable, let pipelineState = pipelineState, let indexBuffer = indexBuffer, let descriptor = view.currentRenderPassDescriptor else { return }
time += 1 / Float(view.preferredFramesPerSecond)
let animateBy = abs(sin(time) / 2 + 0.5) constants.animateBy = animateBy
let commandBuffer = commandQueue.makeCommandBuffer() let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: view.currentRenderPassDescriptor!)
commandEncoder?.setRenderPipelineState(pipelineState) commandEncoder?.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
commandEncoder?.setVertexBytes(&constants, length: MemoryLayout<Constants>.stride, index: 1)
commandEncoder?.drawIndexedPrimitives(type: .triangle, indexCount: indices.count, indexType: .uint16, indexBuffer: indexBuffer, indexBufferOffset: 0)
commandEncoder?.endEncoding() commandBuffer?.present(view.currentDrawable!) commandBuffer?.commit() } }
|