-
-
Save jtbandes/b5bfffffa50c99dfaf91e67e14ee1fab to your computer and use it in GitHub Desktop.
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 Cocoa | |
import MetalKit | |
// Our macOS specific view controller | |
class GameViewController: NSViewController { | |
var renderer: Renderer! | |
var mtkView: MTKView! | |
var displayLink: CVDisplayLink! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
guard let mtkView = self.view as? MTKView else { | |
print("View attached to GameViewController is not an MTKView") | |
return | |
} | |
self.mtkView = mtkView | |
// Select the device to render with. We choose the default device | |
guard let defaultDevice = MTLCreateSystemDefaultDevice() else { | |
print("Metal is not supported on this device") | |
return | |
} | |
mtkView.device = defaultDevice | |
guard let newRenderer = Renderer(metalKitView: mtkView) else { | |
print("Renderer cannot be initialized") | |
return | |
} | |
guard CVDisplayLinkCreateWithActiveCGDisplays(&displayLink) == kCVReturnSuccess, | |
let displayLink = displayLink | |
else { | |
print("unable to create display link") | |
return | |
} | |
guard CVDisplayLinkSetOutputCallback(displayLink, GameViewController._outputCallback, Unmanaged.passUnretained(self).toOpaque()) == kCVReturnSuccess else { | |
fatalError("unable to configure output callback") | |
} | |
renderer = newRenderer | |
renderer.mtkView(mtkView, drawableSizeWillChange: mtkView.drawableSize) | |
mtkView.delegate = renderer | |
mtkView.isPaused = true | |
} | |
// handle display link callback at 60fps | |
static let _outputCallback: CVDisplayLinkOutputCallback = { (displayLink, inNow, inOutputTime, flagsIn, flagsOut, context) -> CVReturn in | |
// convert opaque context pointer back into a reference to our view | |
let vc = Unmanaged<GameViewController>.fromOpaque(context!).takeUnretainedValue() | |
vc.mtkView.draw() | |
return kCVReturnSuccess | |
} | |
override func viewWillAppear() { | |
guard CVDisplayLinkStart(displayLink) == kCVReturnSuccess else { | |
fatalError("unable to start display link") | |
} | |
} | |
override func viewWillDisappear() { | |
if let displayLink = displayLink { | |
CVDisplayLinkStop(displayLink) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment