import Foundation import QuartzCore import UIKit func renderDeinit(_ vm: RenderVM) { vm.timer?.invalidate() vm.timer = nil guard eglMakeCurrentContext(&vm.glView.st) else { return } raybriShutdown() eglMakeCurrent(vm.glView.st.display, nil, nil, nil) eglDestroySurface(vm.glView.st.display, vm.glView.st.surface) eglDestroyContext(vm.glView.st.display, vm.glView.st.ctx) eglTerminate(vm.glView.st.display) } func renderInit(_ vm: RenderVM) { // UIKit has no NSOpenGLContext: EGL/ANGLE renders into the view's layer, // so the layer is what the bridge needs to create its surface from. let layer = Unmanaged.passUnretained(vm.glView.layer).toOpaque() vm.glView.st.caLayer = layer guard eglInit(&vm.glView.st) else { fatalError("ERROR Could not initialize EGL") } guard eglResetSurface(&vm.glView.st) else { fatalError("ERROR Could not reset EGL surface") } guard eglMakeCurrentContext(&vm.glView.st) else { fatalError("ERROR Could not make EGL context current") } raybriInit() } func renderStartTimer(_ vm: RenderVM) { // Make a time mark for calculating time delta vm.startTime = CACurrentMediaTime() // The frame is presented by eglSwapBuffers into the view's layer, not by // CoreGraphics, so the timer drives the rendering itself instead of // invalidating the view for a draw(_:) pass the way macOS does. let timer = Timer(timeInterval: 1.0 / RENDER_FPS, repeats: true) { [weak vm] _ in guard let vm else { return } renderDraw(vm) } vm.timer = timer // .common means holding buttons in UI does not pause this rendering timer RunLoop.main.add(timer, forMode: .common) }