From 1fe9578b3a67781d421fdc6fdc734d17df31b662 Mon Sep 17 00:00:00 2001 From: a dinosaur Date: Mon, 5 Aug 2024 16:44:32 +1000 Subject: [PATCH] add fps counter --- Sources/Voxelotl/Application.swift | 9 ++++++++- Sources/Voxelotl/CMakeLists.txt | 1 + Sources/Voxelotl/FPSCalculator.swift | 18 ++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 Sources/Voxelotl/FPSCalculator.swift diff --git a/Sources/Voxelotl/Application.swift b/Sources/Voxelotl/Application.swift index 76c7c82..d43d0ca 100644 --- a/Sources/Voxelotl/Application.swift +++ b/Sources/Voxelotl/Application.swift @@ -9,6 +9,7 @@ public class Application { private var view: SDL_MetalView? = nil private var renderer: Renderer? = nil private var lastCounter: UInt64 = 0 + private var fpsCalculator = FPSCalculator() private var stderr = FileHandle.standardError @@ -40,6 +41,7 @@ public class Application { view = SDL_Metal_CreateView(window) do { let layer = unsafeBitCast(SDL_Metal_GetLayer(view), to: CAMetalLayer.self) + layer.displaySyncEnabled = cfg.vsyncMode == .off ? false : true self.renderer = try Renderer(layer: layer) } catch RendererError.initFailure(let message) { print("Renderer init error: \(message)", to: &stderr) @@ -92,6 +94,10 @@ public class Application { } private func update(_ deltaTime: Double) -> ApplicationExecutionState { + fpsCalculator.frame(deltaTime: deltaTime) { fps in + print("FPS: \(fps)", to: &stderr) + } + do { try renderer!.paint() } catch RendererError.drawFailure(let message) { @@ -99,6 +105,7 @@ public class Application { } catch { print("Renderer draw error: unexpected error", to: &stderr) } + return .running } @@ -140,7 +147,7 @@ public struct ApplicationConfiguration { static let highDPI = Flags(rawValue: 1 << 1) } - public enum VSyncMode { + public enum VSyncMode: Equatable { case off case on(interval: UInt) case adaptive diff --git a/Sources/Voxelotl/CMakeLists.txt b/Sources/Voxelotl/CMakeLists.txt index 146117b..475d7f5 100644 --- a/Sources/Voxelotl/CMakeLists.txt +++ b/Sources/Voxelotl/CMakeLists.txt @@ -1,6 +1,7 @@ add_executable(Voxelotl MACOSX_BUNDLE Assets.xcassets Renderer.swift + FPSCalculator.swift Application.swift main.swift) diff --git a/Sources/Voxelotl/FPSCalculator.swift b/Sources/Voxelotl/FPSCalculator.swift new file mode 100644 index 0000000..812765d --- /dev/null +++ b/Sources/Voxelotl/FPSCalculator.swift @@ -0,0 +1,18 @@ +import Foundation + +public struct FPSCalculator { + private var _accumulator = 0.0 + private var _framesCount = 0 + + public mutating func frame(deltaTime: Double, result: (_ fps: Int) -> Void) { + _framesCount += 1 + _accumulator += deltaTime + + if (_accumulator >= 1.0) { + result(_framesCount) + + _framesCount = 0 + _accumulator = fmod(_accumulator, 1.0) + } + } +}