Created
October 3, 2021 21:41
-
-
Save menangen/f955b8756830159c6512ceebf63bb4d6 to your computer and use it in GitHub Desktop.
Apple Metal Square rotation with Aspect ratio
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
// Created by menangen on 02.11.2018. | |
// Copyright © 2018 menangen. All rights reserved. | |
// | |
import MetalKit | |
class TriangleRenderer: NSObject, MTKViewDelegate { | |
public let device: MTLDevice | |
let commandQueue: MTLCommandQueue | |
var pipelineState: MTLRenderPipelineState! | |
var fpsCount: Float = 0.0 | |
init?(metalKitView: MTKView) { | |
self.device = metalKitView.device! | |
self.commandQueue = self.device.makeCommandQueue()! | |
let library = device.makeDefaultLibrary() | |
let pipelineDescriptor = MTLRenderPipelineDescriptor() | |
pipelineDescriptor.colorAttachments[0].pixelFormat = metalKitView.colorPixelFormat | |
pipelineDescriptor.vertexFunction = library!.makeFunction(name: "vertex_main") | |
pipelineDescriptor.fragmentFunction = library!.makeFunction(name: "fragment_main") | |
pipelineDescriptor.sampleCount = 1 | |
do { | |
pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor) | |
} catch { | |
print("Error with device.makeRenderPipelineState") | |
} | |
super.init() | |
} | |
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { | |
let aspect = Float(size.width) / Float(size.height) | |
} | |
func draw(in view: MTKView) { | |
guard let commandBuffer = commandQueue.makeCommandBuffer() else { return } | |
guard let passDescriptor = view.currentRenderPassDescriptor else { return } | |
guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor) else { return } | |
let vertexData: [Float] = [ | |
-0.5, 0.5, | |
0 + self.fpsCount, 1.0 - self.fpsCount, 0.25 + self.fpsCount, | |
-0.5, -0.5, | |
0 + self.fpsCount * 0.5, self.fpsCount, 0.75, | |
0.5, 0.5, | |
0 + self.fpsCount * 0.2, 0.15 + self.fpsCount * 0.5, 1.0 - self.fpsCount, | |
0.5, -0.5, | |
0.6 + self.fpsCount * 0.2, 0.5, 0.8 - self.fpsCount * 0.15 | |
] | |
encoder.setVertexBytes(vertexData, length: vertexData.count * MemoryLayout<Float>.stride, index: 0) | |
encoder.setRenderPipelineState(pipelineState) | |
encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) | |
encoder.endEncoding() | |
commandBuffer.present(view.currentDrawable!) | |
commandBuffer.commit() | |
self.fpsCount += 0.001 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment